|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 只为 于 2017-8-29 21:50 编辑
1、列表的一些常用操作符
1)比较操作符
- >>>list1=[123,456]
- >>>list2=[234,123]
- >>>list1>list2
- False
复制代码
注意:list比较的话,当有多个元素的时候,默认是从第0个元素开始比较的,只有第0个元素list1小,整个列表都小,不用考虑后边的元素。跟字符串的比较一样,比较ASCII码的大小
- >>> list1 = [123,456]
- >>> list3 = ['a']
- >>> list1>list3
- Traceback (most recent call last):
- File "<pyshell#5>", line 1, in <module>
- list1>list3
- TypeError: unorderable types: int() > str()
- >>> list3 = ['a']
- >>> list5 = [True]
- >>> list3 > list5
- Traceback (most recent call last):
- File "<pyshell#11>", line 1, in <module>
- list3 > list5
- TypeError: unorderable types: str() > bool()
- >>> list5 = [True]
- >>> list6=[None]
- >>> list5>list6
- Traceback (most recent call last):
- File "<pyshell#17>", line 1, in <module>
- list5>list6
- TypeError: unorderable types: bool() > NoneType()
复制代码
note:经多次试验,只有当列表中的首元素数据类型相同时,才能进行算术运算操作
2)逻辑操作符
- >>> list1 = [123,456]
- >>> list2=[234]
- >>> list3 = [123,456]
- >>> (list1<list2) and (list1==list3)
- True
复制代码
3)连接操作符 +
注意:有些事违规的,不能添加新元素,+ 连接符两边的数据类型必须一致的
- >>> list1 = [123,456]
- >>> list1 + '小甲鱼'
- Traceback (most recent call last):
- File "<pyshell#1>", line 1, in <module>
- list1 + '小甲鱼'
- TypeError: can only concatenate list (not "str") to list
- >>>
复制代码
建议:列表之间不要使用连接操作符,使用extend()方法
4)重复操作符 *
- >>> list3 = [123,456]
- >>> list3*3
- [123, 456, 123, 456, 123, 456]
- >>> list3
- [123, 456]
- >>> list3 *=3
- >>> list3
- [123, 456, 123, 456, 123, 456]
复制代码
5)成员关系操作符 in ,not in
- >>> list1=[123,['小甲鱼','二货'],True,None]
- >>> 123 in list1
- False
- >>> '小甲鱼' in list1
- False
- >>> '小甲鱼' in list[1]
- True
- >>> lis1t[1][1]
- '二货'
复制代码
2、列表的小伙伴们(官方:列表类型的内置函数)
属于列表(某一个对象)的内置函数,用点记法使用。
1)count(list)--->int
2)index()--->int index(元素,start, end)
常用的:
3)reverse()--->list 反转
4)sort()--->list 默认从小到大排序
list.sort(func,key,reverse=False) 前两个参数是默认的,可以不写的,reverse默认是False
list.sort(reverse=True) 相当于先sort()排序,在reverse()反转的效果
关于分片‘拷贝’补充:
- >>> list3=[9,8,7,4,2,0]
- >>> list4 = list3[:]
- >>> list4
- [9, 8, 7, 4, 2, 0]
- >>> list5=list3
- >>> list5
- [9, 8, 7, 4, 2, 0]
- >>> list3.sort()
- >>> list3
- [0, 2, 4, 7, 8, 9]
- >>> list4
- [9, 8, 7, 4, 2, 0]
- >>> list5
- [0, 2, 4, 7, 8, 9]
复制代码
注意:如果需要拷贝,使用分片的形式 |
评分
-
查看全部评分
|