# python中的list用法简单小结

>>>li = ['a', 'b', 'c']

>>>li.extend(['d', 'e', 'f'])

>>>li

['a','b', 'c', 'd', 'e', 'f']

>>>li[-1]

'f'

>>>li.append(['d', 'e', 'f'])

>>>li

['a','b', 'c', ['d', 'e', 'f']]

li.insert(i,x) 在标号为i的元素处添加list x

li.remove(x)删除list x从li

li.pop([i]): 如果i缺省则删除list最后一个元素，如果不赋值，则删除标号为i的元素，这里'[]'表明i的赋值是可以选择的，非必须赋值变量

li.count(x):计算x出现的次数

li.sort():为li中所有元素排序

li.reverse():将li中所有元素反序

>>> a=[66.25,333,333,1,1234.5]

>>> printa.count(333),a.count(66.25),a.count('x')

2 1 0

>>> a.insert(2,-1)

>>> a.append(333)

>>> a[66.25, 333, -1, 333, 1, 1234.5, 333]

>>> a.index(333)

1

>>> a.remove(333)

>>> a[66.25, -1, 333, 1, 1234.5, 333]

>>> a.reverse()

>>> a

[333, 1234.5, 1, 333, -1, 66.25]

>>> a.sort()

>>> a

[-1, 1, 66.25, 333, 333, 1234.5]

list用成栈----先进后出

li.append

li.pop

list用成队列 要用collections.deque---先进先出

>>> from collections import deque

>>> queue=deque(["Eric","John","Michael"])

>>> queue.append("Terry")   # Terry arrives

>>> queue.append("Graham")  # Graham arrives

>>> queue.popleft()  # The first to arrive now leaves'Eric'

>>> queue.popleft()  # The second to arrive now leaves'John'

>>> queue     # Remaining queue in order of arrival

deque(['Michael', 'Terry', 'Graham'])

filter(function,sequence)

e.g.

>>> deff(x):returnx%2!=0andx%3!=0

...

>>> filter(f,range(2,25))

[5, 7, 11, 13, 17, 19, 23]

filter函数适用于逻辑函数，返回的是在range范围内，即2-24(包含)中使得f函数为真的值

map(function,sequence)

e.g.

>>> defcube(x):returnx*x*x

...

>>> map(cube,range(1,11))

[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

map函数适用于对list整个处理，如果输入参数是两个变量的话，可以用map(cube,range1,range2)

reduce(function,sequence)

e.g.

...

55

e.g.1 >>>squares=[x**2 for x in range(10)]

e.g.2 >>> [(x,y)for x in[1,2,3]for y in [3,1,4]if x!=y]

e.g.3 >>> vec=[[1,2,3],[4,5,6],[7,8,9]]

>>> [num for elem in vec for num in elem]

[1, 2, 3, 4, 5, 6, 7, 8, 9]

e.g.4>>> matrix=[

... [1,2,3,4],

... [5,6,7,8],

... [9,10,11,12],

...]

>>> [[row[i] for row in matrix] for i in range(4)]

[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

>>> zip(*matrix)

[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

https://blog.sciencenet.cn/blog-571755-706769.html

## 全部精选博文导读

GMT+8, 2024-9-15 14:08