gpt4 book ai didi

python - 有没有比使用 for 循环更干净的方法

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

我想知道是否有任何其他方法可以循环和操作位于单独数组中的数据。

import numpy as np

a = np.arange(2)
b = np.arange(5)
c = np.arange(5)

l1 = []
for x in a:
l2 = []
for y in b:
l3 = []
y = x + 1
for z in c:
z = x + y
t = (x,y,z)
l3.append(t)
l2.append(l3)
l1.append(l2)
print l1

最佳答案

此代码完全符合您的要求。

def method(lst, range1, range2):
for i in lst:
yield [[(i, i+1, 1+(i*2))]*range2]*range1

甚至可以变成生成器表达式:

def gen_method(lst, r1, r2):
return ([[(i, i+1, 1+(i*2))]*r2]*r1 for i in lst)

如果喜欢,请自己测试。


我的测试:

a = range(2)
b = range(5)
c = range(5)

def your_method(a, b, c):
l1 = []
for x in a:
l2 = []
for y in b:
l3 = []
y = x + 1
for z in c:
z = x + y
t = (x,y,z)
l3.append(t)
l2.append(l3)
l1.append(l2)
return l1

def my_method(lst, range1, range2):
for i in lst:
yield [[(i, i+1, 1+(i*2))]*range2]*range1

yours = your_method(a, b, c)
mine = list(my_method(a, len(b), len(c)))

print yours
print '==='
print mine
print '==='
print yours == mine

>>>
[[[(0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1)], [(0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1)], [(0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1)], [(0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1)], [(0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1)]], [[(1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3)], [(1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3)], [(1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3)], [(1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3)], [(1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3)]]]
===
[[[(0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1)], [(0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1)], [(0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1)], [(0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1)], [(0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1), (0, 1, 1)]], [[(1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3)], [(1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3)], [(1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3)], [(1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3)], [(1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3)]]]
===
True

关于python - 有没有比使用 for 循环更干净的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15873350/

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