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

Tani ·
更新时间:2024-09-21
· 513 次阅读

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

以上实例输出结果:

['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']

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

以上实例输出结果:

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 您可能感兴趣的文章:python通过加号运算符操作列表的方法python中list列表的高级函数python 禁止函数修改列表的实现方法python通过apply使用元祖和列表调用函数实例Python列表list内建函数用法实例分析【insert、remove、index、pop等】Python 利用内置set函数对字符串和列表进行去重的方法Python中max函数用于二维列表的实例对python中两种列表元素去重函数性能的比较方法python操作列表的函数使用代码详解Python入门教程3. 列表基本操作【定义、运算、常用函数】Python获取时间范围内日期列表和周列表的函数Python学习笔记之列表和成员运算符及列表相关方法详解



运算符 位运算 列表 位运算符 Python

需要 登录 后方可回复, 如果你还没有账号请 注册新账号