如何使用嵌套的for循环和IF AND语句修复列表推导

时间:2019-08-20 15:54:24

标签: python list-comprehension

为减少这些for循环+ if / else语句的计算时间,我尝试创建一个列表理解。但是,它无法正常运行。

结果应为长度为15的列表,因此不包括X和W的任何t值(0,1,2)。

以下作品:

c = ["X", "Y"]
l = ["Z", "Q", "W"]
t = [0,1,2]
index = 0

for i in c:
    for j in l:
        for k in t:
            if i == "X" and j == "W":
                index = index
            else:
                state[index] = len(Data_frame.loc[(Data_frame["ColunmName1"] == i) & (Data_frame["ColunmName2"] == j) & (Data_frame["ColunmName3"] == k)]) 
                index += 1

我尝试通过以下方式将其转换为列表理解,但这种方法不起作用:

state = [len(current_orderlist.loc[(Data_frame["ColunmName1"]  == i) & Data_frame["ColunmName2"] == j) & (Data_frame["ColunmName3"]  == k)])  for i in c for j in l for k in if i != "X" and j != "W"]

结果:

state = [0, 0, 0, 0, 0]

1 个答案:

答案 0 :(得分:0)

from itertools import product

c = ["X", "Y"]
l = ["Z", "Q", "W"]
t = [0, 1, 2]
index = 0

使用itertools.product:

[x for x in product(c, l, t)]

所有组合的输出:

[('X', 'Z', 0),
 ('X', 'Z', 1),
 ('X', 'Z', 2),
 ('X', 'Q', 0),
 ('X', 'Q', 1),
 ('X', 'Q', 2),
 ('X', 'W', 0),
 ('X', 'W', 1),
 ('X', 'W', 2),
 ('Y', 'Z', 0),
 ('Y', 'Z', 1),
 ('Y', 'Z', 2),
 ('Y', 'Q', 0),
 ('Y', 'Q', 1),
 ('Y', 'Q', 2),
 ('Y', 'W', 0),
 ('Y', 'W', 1),
 ('Y', 'W', 2)]

您的循环:

for i, j, k in product(c, l, t):
    if i == "X" and j == "W":
        index = index
    else:
        print(index, i, j, k)
        index+=1

您与list comprehension的循环:

[[i, j, k] for i, j, k in product(c, l, t) if (i, j) != ('X', 'W')]

list comprehension的输出:

[['X', 'Z', 0],
 ['X', 'Z', 1],
 ['X', 'Z', 2],
 ['X', 'Q', 0],
 ['X', 'Q', 1],
 ['X', 'Q', 2],
 ['Y', 'Z', 0],
 ['Y', 'Z', 1],
 ['Y', 'Z', 2],
 ['Y', 'Q', 0],
 ['Y', 'Q', 1],
 ['Y', 'Q', 2],
 ['Y', 'W', 0],
 ['Y', 'W', 1],
 ['Y', 'W', 2]]
  • DataFrame不可用,所以我没有尝试重新创建