上篇文章:
本次分享在python中常用的list 列表
正文
List(列表) 是 Python 中使用最频繁的数据类型。
列表可以完成大多数集合类的数据结构实现。列表中元素的类型可以不相同,它支持数字,字符串甚至可以包含列表(所谓嵌套)。
列表是写在方括号 [] 之间、用逗号分隔开的元素列表。
如何定义呢
>>> listone=[1,2]
>>> listtwo=['1',2],
>>> listtree=['1','2']
>>> listfor=[1,2,[1]]
打印下对应的结果
>>> print(listone)
[1, 2]
>>> print(listtwo)
(['1', 2],)
>>> print(listtree)
['1', '2']
>>> print(listfor)
[1, 2, [1]]
这样就完成了定义,我们想要获取其中的一些数据,如何获取呢
>>> listone[1:]
[2]
>>> listone[-1:]
[2]
注:list索引从0开始。-1代表获取最后一个
对list通过索引的方式进行反转
>>> listone
[1, 2, 3, 11]
>>> listone[-1:2:-1]
[11]
>>> listone[::-1]
[11, 3, 2, 1]
list中还有有什么方法呢
>>> dir(list)
['__add__', '__class__',
'__contains__',
'__delattr__', '__delitem__',
'__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__iadd__',
'__imul__', '__init__', '__init_subclass__',
'__iter__', '__le__', '__len__', '__lt__', '__mul__',
'__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__reversed__', '__rmul__', '__setattr__',
'__setitem__', '__sizeof__', '__str__', '__subclasshook__',
'append', 'clear', 'copy', 'count', 'extend', 'index',
'insert', 'pop', 'remove', 'reverse', 'sort']
list增加元素
>>> listone.append(1)
>>> listone
[1, 2, 1]
list清空
>>> listone.clear()
>>> listone
[]
list复制
>>> listone=[1,2]
>>> listfive=listone.copy()
>>> listfive
[1, 2]
list中的数量
>>> listone=[1,2]
>>> listfive.count(1)
1
>>> listone.count(1)
1
>>> listone=[1,2]
>>> listone.count(1)
1
>>> listone.append(1)
>>> listone.count(1)
2
>>> listone.append(11)
>>> listone.count(1)
2
可以获取到对应元素在list中的个数.
两个列表的合并
>>> listfive=[2,3]
>>> listone.extend(listfive)
>>> listone
[1, 2, 1, 11, 2, 3]
append可以增加,那么insert也可以增加,可以增加到指定的位置
>>> listone
[1, 2, 1, 11, 2, 3]
>>> listone.insert(2,222)
>>> listone
[1, 2, 222, 1, 11, 2, 3]
元素在的索引,
>>> listone
[1, 2, 222, 1, 11, 2, 3]
>>> listone.index(2)
1
默认返回第一个匹配的元素的索引
删除第三个的元素
>>> listone
[1, 2, 1, 11, 2, 3]
>>> listone.pop(2)
1
>>> listone
[1, 2, 11, 2, 3]
那么要移除对应的元素呢
>>> listone
[1, 2, 11, 2, 3]
>>> listone.remove(2)
>>> listone
[1, 11, 2, 3]
可以看到remove即可,但是remove删除的是第一个匹配到的元素,和index是一样的。
对list进行旋转
>>> listone
[1, 11, 2, 3]
>>> listone.reverse()
>>> listone
[3, 2, 11, 1]
list排序
>>> listone
[3, 2, 11, 1]
>>> listone.sort()
>>> listone
[1, 2, 3, 11]
判断元素是否在
>>> listone
[1, 2, 3, 11]
>>> 2 in listone
True
>>> listone.__contains__(2)
True
两种方式都可以。
获取list长度
>>> listone
[1, 2, 3, 11]
>>> listone.__len__()
4
>>> len(listone)
4
两种方式都可以正常的获取list的长度。
常用的方式都列举了完毕,大部分都是在实际的工作中经常使用的。需要大量的使用。