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

WBOY
Libérer: 2016-06-06 11:14:21
original
1032 Les gens l'ont consulté

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 # 打印组合的列表

Copier après la connexion

以上实例输出结果:

['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']
Copier après la connexion

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

Copier après la connexion

以上实例输出结果:

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
Copier après la connexion

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!