python3 列表属性
1、合并
>>> l1=[1,2,3,'e']
>>> l2=['f',34,'feel']
>>> l1+l2
[1, 2, 3, 'e', 'f', 34, 'feel']
2、重复
>>> l1
[1, 2, 3, 'e']
>>> l1*2
[1, 2, 3, 'e', 1, 2, 3, 'e']
3、增加 append extend
>>> l1=[1,2,3,'e']
>>> l1.append(4)
>>> l1
[1, 2, 3, 'e', 4]
>>> l2=['hello','world']
>>> l1.extend(l2)
>>> l1
[1, 2, 3, 'e', 4, 'hello', 'world']
插入 insert 插入位置 插入内容
>>> l2.insert(2,'a')
>>> l2
['hello', 'world', 'a']
>>> l2.insert(4,'a')
>>> l2
['hello', 'world', 'a', 'a']
4、计数 L.count
>>> l2
['hello', 'world', 'a', 'a']
>>> help(list.insert)
>>> l2.count('a')
2
>>> l2.count('l')
0
5、搜索位置 L.index
index(...)
L.index(value, [start, [stop]]) -> integer -- return first index of value.
>>> l2
['hello', 'world', 'a', 'a']
>>> l2.index('a')
2
6、排序 sort
>>> l2
['hello', 'world', 'a', 'a']
>>> l2.sort()
>>> l2
['a', 'a', 'hello', 'world'] 直接改变列表
>>> l2.sort(reverse=True) 倒序排序设置reverse为True
>>> l2
['world', 'hello', 'a', 'a']
反转 reverse 切片
>>> l2
['world', 'hello', 'a', 'a']
>>> l2.reverse()
>>> l2
['a', 'a', 'hello', 'world']
>>> l2[::-1]
['world', 'hello', 'a', 'a']
7、删除元素
>>> l2
['a', 'a', 'hello', 'world']
>>> del l2[0]
>>> l2
['a', 'hello', 'world']
>>> l2.remove('hello') 按值删除
>>> l2
['a', 'world']
>>> l1=['a','hello',1,4,34,'er']
>>> l1.pop() 默认删除最后一个元素,
'er'
>>> l1
['a', 'hello', 1, 4, 34]
>>> l1.pop(0) 按索引删除
'a'
>>> l1
['hello', 1, 4, 34]
8、使用切片修改元素
>>> l1=[1,2,3,4,5,6,7,8,9,10]
>>> l1[0:8:2]=['a'] 不连续元素
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: attempt to assign sequence of size 1 to extended slice of size 4
>>> l1[0:8:2]=['a','b','c','d']
>>> l1
['a', 2, 'b', 4, 'c', 6, 'd', 8, 9, 10]
>>> l1=[1,2,3,4,5,6,7,8,9,10]
>>> l1[1:3]=['a'] 连续元素
>>> l1
[1, 'a', 4, 5, 6, 7, 8, 9, 10]
9、列表推导
>>> L=[x**2 for x in range(1,10) if x%2!=0]
>>> L
[1, 9, 25, 49, 81]
10、列表生成 list
>>> a=list('hello')
>>> a
['h', 'e', 'l', 'l', 'o']