初步认识Python中的列表与位运算符

WBOY
Release: 2016-06-06 11:14:21
Original
1030 people have browsed it

Python列表
List(列表) 是 Python 中使用最频繁的数据类型。
列表可以完成大多数集合类的数据结构实现。它支持字符,数字,字符串甚至可以包含列表(所谓嵌套)。
列表用[ ]标识。是python最通用的复合数据类型。看这段代码就明白。
列表中的值得分割也可以用到变量[头下标:尾下标],就可以截取相应的列表,从左到右索引默认0开始的,从右到左索引默认-1开始,下标可以为空表示取到头或尾。
加号(+)是列表连接运算符,星号(*)是重复操作。如下实例:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']

print list # 输出完整列表
print list[0] # 输出列表的第一个元素
print list[1:3] # 输出第二个至第三个的元素 
print list[2:] # 输出从第三个开始至列表末尾的所有元素
print tinylist * 2 # 输出列表两次
print list + tinylist # 打印组合的列表

Copy after login

以上实例输出结果:

['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Copy after login

Python位运算符
按位运算符是把数字看作二进制来进行计算的。Python中的按位运算法则如下:

以下实例演示了Python所有位运算符的操作:

#!/usr/bin/python

a = 60      # 60 = 0011 1100 
b = 13      # 13 = 0000 1101 
c = 0

c = a & b;    # 12 = 0000 1100
print "Line 1 - Value of c is ", c

c = a | b;    # 61 = 0011 1101 
print "Line 2 - Value of c is ", c

c = a ^ b;    # 49 = 0011 0001
print "Line 3 - Value of c is ", c

c = ~a;      # -61 = 1100 0011
print "Line 4 - Value of c is ", c

c = a << 2;    # 240 = 1111 0000
print "Line 5 - Value of c is ", c

c = a >> 2;    # 15 = 0000 1111
print "Line 6 - Value of c is ", c

Copy after login

以上实例输出结果:

Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!