[reprint] Python - list comprehension

ShaderJoy 2022-08-06 07:36:57 阅读数:247

reprintpythonlistcomprehension

版权声明:本文为CSDN博主「那一定会很酷」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明.
原文链接:blog.csdn.net/weixin_5227…

Python 列表推导式

一.Why learn list comprehensions 母鸡啊

  1. List comprehensions can be said in PythonIt is widely used in program development.
  2. List comprehensions can be used in a very concise way to quickly generate lists that satisfy specific needs,And the code is very readable.
  3. Python的内部实现对列表推导式做了大量优化,Can guarantee fast running speed.

二.Start learning about list comprehensions 快醒醒

语法

[表达式 for 变量 in 序列或迭代对象]

列表推导式在逻辑上相当于一个循环,But the form is more concise

具体操作:

① 简单举例

>>> list = [x*x for x in range(10)]
>>> print(list)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> print(sum(list))
285
复制代码

② 使用列表推导式实现嵌套列表的平铺

>>> vec = [[1,2,3],[4,5,6],[7,8,9]]
>>> list = [num for elem in vec for num in elem]
>>> print(list)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
''' 在这个列表推导式中有两个循环,其中第一个循环为外循环,执行得慢; 第二个循环为内循环,执行得快. '''
#用循环实现其等价写法:
vec = [[1,2,3],[4,5,6],[7,8,9]]
result= []
for elem in vec:
for num in elem:
result.append(num)
print(result)
复制代码

③ 过滤不符合条件的元素

在列表推导式中可以使用 if 子句来进行筛选,只在结果列表中保留符合条件的元素.

>>> list = [1,2,3,45,6,7,7,8,90,22]
>>> list = [i for i in list if i >10] #if条件判断
>>> list
[45, 90, 22]
>>> list = [x*x if x%2 != 0 else x for x in[1,2,3,4,5]] #if-else条件判断
>>> list
[1, 2, 9, 4, 25]
#List of known grades to find the highest scoring students
scores = {'zhangsan':11,"lisi":22,"wanngwu":33}
highest = max(scores.values())
highestperson = [name for name,score in scores.items() if score == highest]
print(highestperson)
#Use a list comprehension to find the position of the largest element in a list
>>> from random import randint
>>> x = [randint(1,10) for i in range(10)]#randint(1,10)是在1-10之间随机生成一个数,后面range(10)The role is to cycle10次
>>> x
[2, 6, 5, 9, 7, 4, 8, 3, 1, 5]
>>> m = max(x)
>>> m
9
>>> index_l = [index for index,value in enumerate(x) if value == m]
>>> index_l
[3]
复制代码

④ 使用多个循环实现多序列元素的任意组合

>>> l = [(x,y) for x in[1,2,3] for y in[3,2,4] if x != y]
>>> l
[(1, 3), (1, 2), (1, 4), (2, 3), (2, 4), (3, 2), (3, 4)]
''' 对于包含多个循环的列表推导式,Be sure to understand the execution order or nesting relationship of multiple loops '''
复制代码

⑤ 使用列表推导式实现矩阵转置

>>> matrix = [[1,2,3],[4,5,6],[7,8,9]]
>>> re_matrix = [[row[i] for row in matrix]for i in range(3)]
>>> re_matrix
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
复制代码

⑥ 列表推导式中可以使用函数或复杂表达式

def f(v):
if v%2 == 0:
v *= 2
else:
v += 1
return v
print([f(v) for v in [-1,0,1,2,3] if v > 0])
print([v*2 if v%2==0 else v+1 for v in [-1,0,1,2,3] if v > 0])
复制代码

⑦ 列表推导式支持文件对象迭代

>>> fp = open("D:\各种文件\课程设计\Zhengzhou's 14th Five-Year Plan.txt",'r',encoding = 'utf-8')
>>> print([line for line in fp])
#Read result is too long,省略
>>> fp.close()
复制代码

三. Ask a simple question to practice

应用1:使用列表推导式生成 100 以内的所有素数

要求:One line of code kills it!

>>> import math
>>> l = [p for p in range(2,100) if 0 not in[p%d for d in range(2, int(math.sqrt(p))+1)]]
>>> l
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
复制代码

I'm not cheating,The core code is indeed one line(傲娇 )

应用2:实现矩阵转置

matrix = [[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12]]
print("原矩阵:",matrix)
print("转置矩阵为:",[[row[i] for row in matrix] for i in range(4)])
复制代码
版权声明:本文为[ShaderJoy]所创,转载请带上原文链接,感谢。 https://pythonmana.com/2022/218/202208060733407360.html