Python列表的一些常用操作符简单介绍
1.比较操作符可以看到,列表有一个元素那就直接比较,如果有多个元素,那么只比较第0个元素的结果,并作为最终的结果,后面的不在比较
[*]>>> list1=[123]
[*]>>> list2=[234]
[*]>>> list1<list2
[*]True
[*]>>> list1=[123,456]
[*]>>> list2=[234,123]
[*]>>> list1<list2
[*]True
2.逻辑操作符
这个就不用说了,很容易就能看出来,其他的逻辑操作符同理
[*]>>> list3=[123,456]
[*]>>> (list1<list2)and(list1==list3)
[*]True
3.连接操作符
[*]>>> list4=list1+list2
[*]>>> list4
[*][123, 456, 234, 123]
[*]>>> list4+"lw"
[*]
[*]Traceback (most recent call last):
[*]File "<pyshell#11>", line 1, in <module>
[*] list4+"lw"
[*]TypeError: can only concatenate list (not "str") to list
[*]>>>
+可以进行拼接,和extend类似,但是又不同,+两边的对象的类型必须相同,如果不同就会报错,如果添加元素到列表中可以用append或者insert方法
[*]>>> list3
[*][123, 456]
[*]>>> list3*3
[*][123, 456, 123, 456, 123, 456]
[*]>>> list3*=3
[*]>>> list3
[*][123, 456, 123, 456, 123, 456]
4.成员关系操作符
[*]>>> 123 in list3
[*]True
[*]>>> "lw" not in list3
[*]True
再试一个
[*]>>> list5=[123,["lw"],456]
[*]>>> "lw" in list3
[*]False
为什么这样就不行呢?因为lw是在list5列表中的列表中,不是在list5这个列表中,当然会出错了,正确的方式是这样
[*]>>> "lw" in list5[1][0]
[*]True
[*]>>> "lw" in list5[1]
[*]True
列表的内置函数
[*]>>> dir(list)
[*]['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
1.统计出现了多少次count
[*]>>> list3
[*][123, 456, 123, 456, 123, 456]
[*]>>> list3.count(123)
[*]3
[*]>>> list5
[*][123, ['lw'], 456]
[*]>>> list5.count("lw")
[*]0
[*]>>> list5.count(["lw"])
[*]1
2.返回参数在列表中的位置索引index
[*]>>> list3
[*][123, 456, 123, 456, 123, 456]
[*]>>> list3.index (123)
[*]0
这里显示的是123第一次出现的位置,但是其实他有三个参数 index(匹配参数,开始位置,结束位置)就是在位置之间显示该参数出现的次数;如果只写第一个,那么就表示第一次出现的位置,其他位置出现的不再算;
[*]>>> list3.index (123,1,4)
[*]2
3.将整个列表逆转排列reverse
[*]>>> list3.reverse ()
[*]>>> list3
[*][456, 123, 456, 123, 456, 123]
4.指定的方式将列表元素排序sort
[*]>>> list6=[4,2,5,3,6,1,0]
[*]>>> list6.sort()
[*]>>> list6
[*][0, 1, 2, 3, 4, 5, 6]
可以看到sort是将列表元素从小到大排序,那么,问题来了,如何让元素从大到小排序呢
方法1:sort排序后用reverse逆序排列
[*]>>> list6.reverse ()
[*]>>> list6
[*][6, 5, 4, 3, 2, 1, 0]
方法2:用sort的三个参数实现 sort(func,key,reverse)其中func指定排序的算法,key表示跟这个算法搭配的关键字(默认为归并排序),reverse默认为false表示没有逆序,改为true的话表示逆序,func和key都是默认的可以不管只改最后一个参数
[*]>>> list6.sort(reverse=True)
[*]>>> list6
[*][6, 5, 4, 3, 2, 1, 0]
注意true的大小写
页:
[1]