gpt4 book ai didi

python - 嵌套 for 循环以列出具有不同 "if"条件的理解

转载 作者:太空宇宙 更新时间:2023-11-03 13:07:25 24 4
gpt4 key购买 nike

我正在尝试将此嵌套循环转换为列表推导式,但我不确定是否可行,因为“tmp”列表中的项目可能有不同的值。这是最好的方法吗?谢谢!

final = []
for a in range(-13, 1):
for b in range(0,4):
for c in range(6, 49):
for d in range(48, 94):
tmp = [0 for i in range(100)]
for i in range(100):
if raw_x[i] >= b and raw_y[i] >= d:
tmp [i] = -1
if raw_x[i] <= a and raw_y[i] <= c:
tmp [i] = 1
final.append(tmp)

最佳答案

嵌套推导的可读性不是很好

一个简单的

[something for something in container if something > 9]

很棒,但嵌套的常常令人困惑

你可以简单地将循环移动到一个生成器函数中——它仍然是可读的并且允许惰性迭代

def no_idea_what_this_represents():
for a in range(-13, 1):
for b in range(0,4):
for c in range(6, 49):
for d in range(48, 94):
tmp = [0 for i in range(100)]
for i in range(100):
if raw_x[i] >= b and raw_y[i] >= d:
tmp [i] = -1
if raw_x[i] <= a and raw_y[i] <= c:
tmp [i] = 1
yield tmp

final = [signs for signs in no_idea_what_this_represents()]

编辑:只是一个自以为是的附录——这样就可以命名复杂的嵌套循环(出于显而易见的原因,我将其命名为 no_idea_what_this_represents)但是当程序员看到

possible_views = [matrix for matrix in camera_matrices()]

他马上就知道这是什么意思了

possible_views = [device.matrix 
for devices in itertools.chain(connected_devices(), buffered_devices()
for device in devices
if device.type=='camera']

让程序员读了很多行并且不清楚发生了什么

关于python - 嵌套 for 循环以列出具有不同 "if"条件的理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54076739/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com