Python列表生成式12个小功能,你常用哪几个?
作者 | zglg
来源 | Python与算法社区
python里[]
表示一个列表,对容器类型的数据进行运算和操作,生成新的列表最高效、快速的办法,就是列表生成式。
它优雅、简洁,值得大家多多使用!今天盘点列表生成式在工作中的主要使用场景。
入门
1
range快速生成连续列表
In [1]: a = range(11) In [2]: a Out[2]: range(0, 11) In [3]: list(a) Out[3]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2
对列表里面的数据进行运算后重新生成一个新的列表:
In [5]: a = range(0,11) In [6]: b = [x**2 for x in a] In [7]: b Out[7]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
3
对一个列表里面的数据筛选,只计算[0,11) 中偶数的平方:
In [10]: a = range(11) In [11]: c = [x**2 for x in a if x%2==0] In [12]: c Out[12]: [0, 4, 16, 36, 64, 100]
4
前面列表生成式都只传一个参数x,带有两个参数的运算:
In [13]: a = range(5) In [14]: b = ['a','b','c','d','e'] In [20]: c = [str(y) + str(x) for x, y in zip(a,b)] In [21]: c Out[21]: ['a0', 'b1', 'c2', 'd3', 'e4']
5
结合字典,打印键值对:
In [22]: a = {'a':1,'b':2,'c':3} In [23]: b = [k+ '=' + v for k, v in a.items()] In [24]: b = [k+ '=' + str(v) for k, v in a.items()] In [25]: b Out[25]: ['a=1', 'b=2', 'c=3']
6
输出某个目录下的所有文件和文件夹的名称:
In [33]: [d for d in os.listdir('d:/summary')] Out[33]: ['a.txt.txt', 'python-100']
7
列表中所有单词都转化为小写:
In [34]: a = ['Hello', 'World', '2019Python'] In [35]: [w.lower() for w in a] Out[35]: ['hello', 'world', '2019python']
进阶
8
将值分组:
In [36]: def bifurcate(lst, filter): ...: return [ ...: [x for i,x in enumerate(lst) if filter[i] == True], ...: [x for i,x in enumerate(lst) if filter[i] == False] ...: ] ...: In [37]: bifurcate(['beep', 'boop', 'foo', 'bar'], [True, True, False, True]) Out[37]: [['beep', 'boop', 'bar'], ['foo']]
9
进一步抽象例子8,根据指定函数fn 对lst 分组:
In [38]: def bifurcate_by(lst, fn): ...: return [ ...: [x for x in lst if fn(x)], ...: [x for x in lst if not fn(x)] ...: ] ...: In [39]: bifurcate_by(['beep', 'boop', 'foo', 'bar'], lambda x: x[0] == 'b') Out[39]: [['beep', 'boop', 'bar'], ['foo']]
10
返回可迭代对象的差集,注意首先都把a, b
用set 包装
In [53]: def difference(a, b): ...: _a, _b =set(a),set(b) ...: return [item for item in _a if item not in _b] ...: ...: In [54]: difference([1,1,2,3,3], [1, 2, 4]) Out[54]: [3]
11
进一步抽象10,根据函数fn 映射后选取差集,如下列表元素分别为单个元素和字典的例子:
In [61]: def difference_by(a, b, fn): ...: ...: _b = set(map(fn, b)) ...: ...: return [item for item in a if fn(item) not in _b] ...: ...: ...: In [62]: from math import floor ...: difference_by([2.1, 1.2], [2.3, 3.4],floor) Out[62]: [1.2] In [63]: difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x']) Out[63]: [{'x': 2}]
12
过滤非重复值,结合list 的count( 统计出元素在列表中出现次数):
In [64]: def filter_non_unique(lst): ...: return [item for item in lst if lst.count(item) == 1] In [65]: filter_non_unique([1, 2, 2, 3, 4, 4, 5]) Out[65]: [1, 3, 5]
熟练操作以上12个例子,就算掌握python 中非常有用的列表生成式。
相关推荐
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
huavhuahua 2020-11-20
meylovezn 2020-11-20
逍遥友 2020-11-20
weiiron 2020-11-16