当前位置:Gxlcms > Python > python中list列表高级函数

python中list列表高级函数

时间:2021-07-01 10:21:17 帮助过:74人阅读

这篇文章主要为大家详细介绍了python中list列表的高级函数,感兴趣的小伙伴们可以参考一下

use a list as a stack: #像栈一样使用列表

  1. stack = [3, 4, 5]
  2. stack.append(6)
  3. stack.append(7)
  4. stack
  5. [3, 4, 5, 6, 7]
  6. stack.pop() #删除最后一个对象
  7. 7
  8. stack
  9. [3, 4, 5, 6]
  10. stack.pop()
  11. 6
  12. stack.pop()
  13. 5
  14. stack
  15. [3, 4]

use a list as a queue: #像队列一样使用列表

  1. > from collections import deque #这里需要使用模块deque
  2. > queue = deque(["Eric", "John", "Michael"])
  3. > queue.append("Terry") # Terry arrives
  4. > queue.append("Graham") # Graham arrives
  5. > queue.popleft() # The first to arrive now leaves
  6. 'Eric'
  7. > queue.popleft() # The second to arrive now leaves
  8. 'John'
  9. > queue # Remaining queue in order of arrival
  10. deque(['Michael', 'Terry', 'Graham'])

three built-in functions: 三个重要的内建函数

filter(), map(), and reduce().
1)、filter(function, sequence)::
按照function函数的规则在列表sequence中筛选数据

  1. > def f(x): return x % 3 == 0 or x % 5 == 0
  2. ... #f函数为定义整数对象x,x性质为是3或5的倍数
  3. > filter(f, range(2, 25)) #筛选
  4. [3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24]

2)、map(function, sequence):
map函数实现按照function函数的规则对列表sequence做同样的处理,
这里sequence不局限于列表,元组同样也可。

  1. > def cube(x): return x*x*x #这里是立方计算 还可以使用 x**3的方法
  2. ...
  3. > map(cube, range(1, 11)) #对列表的每个对象进行立方计算
  4. [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

注意:这里的参数列表不是固定不变的,主要看自定义函数的参数个数,map函数可以变形为:def func(x,y) map(func,sequence1,sequence2) 举例:

  1. seq = range(8) #定义一个列表
  2. > def add(x, y): return x+y #自定义函数,有两个形参
  3. ...
  4. > map(add, seq, seq) #使用map函数,后两个参数为函数add对应的操作数,如果列表长度不一致会出现错误
  5. [0, 2, 4, 6, 8, 10, 12, 14]

3)、reduce(function, sequence):
reduce函数功能是将sequence中数据,按照function函数操作,如 将列表第一个数与第二个数进行function操作,得到的结果和列表中下一个数据进行function操作,一直循环下去…
举例:

  1. def add(x,y): return x+y
  2. ...
  3. reduce(add, range(1, 11))
  4. 55

List comprehensions:
这里将介绍列表的几个应用:
squares = [x**2 for x in range(10)]
#生成一个列表,列表是由列表range(10)生成的列表经过平方计算后的结果。
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
#[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] 这里是生成了一个列表,列表的每一项为元组,每个元组是由x和y组成,x是由列表[1,2,3]提供,y来源于[3,1,4],并且满足法则x!=y。

Nested List Comprehensions:
这里比较难翻译,就举例说明一下吧:

  1. matrix = [ #此处定义一个矩阵
  2. ... [1, 2, 3, 4],
  3. ... [5, 6, 7, 8],
  4. ... [9, 10, 11, 12],
  5. ... ]
  6. [[row[i] for row in matrix] for i in range(4)]
  7. #[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

这里两层嵌套比较麻烦,简单讲解一下:对矩阵matrix,for row in matrix来取出矩阵的每一行,row[i]为取出每行列表中的第i个(下标),生成一个列表,然后i又是来源于for i in range(4) 这样就生成了一个列表的列表。

The del statement:
删除列表指定数据,举例:

  1. > a = [-1, 1, 66.25, 333, 333, 1234.5]
  2. >del a[0] #删除下标为0的元素
  3. >a
  4. [1, 66.25, 333, 333, 1234.5]
  5. >del a[2:4] #从列表中删除下标为2,3的元素
  6. >a
  7. [1, 66.25, 1234.5]
  8. >del a[:] #全部删除 效果同 del a
  9. >a
  10. []

Sets: 集合

  1. > basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
  2. >>> fruit = set(basket) # create a set without duplicates
  3. >>> fruit
  4. set(['orange', 'pear', 'apple', 'banana'])
  5. >>> 'orange' in fruit # fast membership testing
  6. True
  7. >>> 'crabgrass' in fruit
  8. False
  9. >>> # Demonstrate set operations on unique letters from two words
  10. ...
  11. >>> a = set('abracadabra')
  12. >>> b = set('alacazam')
  13. >>> a # unique letters in a
  14. set(['a', 'r', 'b', 'c', 'd'])
  15. >>> a - b # letters in a but not in b
  16. set(['r', 'd', 'b'])
  17. >>> a | b # letters in either a or b
  18. set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
  19. >>> a & b # letters in both a and b
  20. set(['a', 'c'])
  21. >>> a ^ b # letters in a or b but not both
  22. set(['r', 'd', 'b', 'm', 'z', 'l'])

Dictionaries:字典

  1. >>> tel = {'jack': 4098, 'sape': 4139}
  2. >>> tel['guido'] = 4127 #相当于向字典中添加数据
  3. >>> tel
  4. {'sape': 4139, 'guido': 4127, 'jack': 4098}
  5. >>> tel['jack'] #取数据
  6. 4098
  7. >>> del tel['sape'] #删除数据
  8. >>> tel['irv'] = 4127 #修改数据
  9. >>> tel
  10. {'guido': 4127, 'irv': 4127, 'jack': 4098}
  11. >>> tel.keys() #取字典的所有key值
  12. ['guido', 'irv', 'jack']
  13. >>> 'guido' in tel #判断元素的key是否在字典中
  14. True
  15. >>> tel.get('irv') #取数据
  16. 4127

也可以使用规则生成字典:

  1. >>> {x: x**2 for x in (2, 4, 6)}
  2. {2: 4, 4: 16, 6: 36}

enumerate():遍历元素及下标
enumerate 函数用于遍历序列中的元素以及它们的下标:

  1. >>> for i, v in enumerate(['tic', 'tac', 'toe']):
  2. ... print i, v
  3. ...
  4. 0 tic
  5. 1 tac
  6. 2 toe

zip():
zip()是Python的一个内建函数,它接受一系列可迭代的对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些tuples组成的list(列表)。若传入参数的长度不等,则返回list的长度和参数中长度最短的对象相同。利用*号操作符,可以将list unzip(解压)。

  1. >>> questions = ['name', 'quest', 'favorite color']
  2. >>> answers = ['lancelot', 'the holy grail', 'blue']
  3. >>> for q, a in zip(questions, answers):
  4. ... print 'What is your {0}? It is {1}.'.format(q, a)
  5. ...
  6. What is your name? It is lancelot.
  7. What is your quest? It is the holy grail.
  8. What is your favorite color? It is blue.

有关zip举一个简单点儿的例子:

  1. >>> a = [1,2,3]
  2. >>> b = [4,5,6]
  3. >>> c = [4,5,6,7,8]
  4. >>> zipped = zip(a,b)
  5. [(1, 4), (2, 5), (3, 6)]
  6. >>> zip(a,c)
  7. [(1, 4), (2, 5), (3, 6)]
  8. >>> zip(*zipped)
  9. [(1, 2, 3), (4, 5, 6)]

reversed():反转

  1. >>> for i in reversed(xrange(1,10,2)):
  2. ... print i
  3. ...

sorted(): 排序

  1. > basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
  2. > for f in sorted(set(basket)): #这里使用了set函数
  3. ... print f
  4. ...
  5. apple
  6. banana
  7. orange
  8. pear

python的set和其他语言类似, 是一个 基本功能包括关系测试和消除重复元素.

To change a sequence you are iterating over while inside the loop (for example to duplicate certain items), it is recommended that you first make a copy. Looping over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:

  1. >>> words = ['cat', 'window', 'defenestrate']
  2. >>> for w in words[:]: # Loop over a slice copy of the entire list.
  3. ... if len(w) > 6:
  4. ... words.insert(0, w)
  5. ...
  6. >>> words
  7. ['defenestrate', 'cat', 'window', 'defenestrate']

以上就是本文的全部内容,希望对大家的学习有所帮助。

更多python中list列表高级函数相关文章请关注PHP中文网!

人气教程排行