我想预先确定itertools组合的条件。
我的问题:我只需要相差100天或更少天的组合。
实际上,我的代码打破了循环。我想删减并继续下一个组合。有可能吗?
from itertools import combinations
for row in combinations(df.values, 5):
E1_date, E2_date, E3_date, E4_date, E5_date = row[0][0], row[1][0], row[2][0], row[3][0], row[4][0]
if E5_date - E1_date > 100:
break
# The combinations must not have more than 100 days of difference
而不是在循环中过滤,请将组合迭代器传递给filter()
。由于您没有提供数据示例,因此使用数据有些困难,但是这里有一个最小的示例,希望可以为您提供足够的想法。
使用filter()
,您只给它一个lambda函数,对于想要的组合,它返回True,对于不需要的组合,它返回False:
filter()
打印:
from itertools import combinations
values = list(range(10))
# all 5 element combinations of 0-9 such that the difference
# between the first and last is less than 6
combos = filter(lambda e: e[4] - e[0] < 6, combinations(values, 5))
for row in combos:
print(row, row[4] - row[0])