用于同时循环三个可供选择的阵列

时间:2017-03-23 16:24:30

标签: python loops for-loop 3d

我想同时遍历三个数字列表,并对每个变量组合进行计算。 所以我以后可以将所有计算的数据存储在一个三维数据帧中。

我试过了:

for (x,y,z) in [(x, y, z) for x in a for y in b for z in c]:

但这似乎不起作用,它只对x和y的每个值执行计算,但不执行z。

我是否也可以同时在z中循环?

3 个答案:

答案 0 :(得分:5)

如何使用zip:

go timer1()

使用具体示例进行更新

for x, y, z in zip(a, b, c):
    # Do something

输出:

users = ['alex', 'john']
uids = [502, 501]
shells = ['bash', 'tcsh']

for user, uid, shell in zip(users, uids, shells):
    print('User: {}, UID: {}, Shell: {}'.format(user, uid, shell))

答案 1 :(得分:1)

如果您想要所有组合,请使用itertools.product

from itertools import product
for x, y, z in product([1, 2], ['A', 'B'], [3, 4]):
    print(x, y, z)

答案 2 :(得分:0)

原来我尝试使用的代码确实有效。只需要列举我的所有输入。

for (x,y,z) in [(x, y, z) for x in a for y in b for z in c]:

可以将其用于具有超过3个维度的数据帧。 itertools.product也适用于多维数组for循环。

感谢大家的回复。