[英]Conditions on itertools combinations Python
I would like to pre definited a condition on itertools combinations.我想预先确定 itertools 组合的条件。
My problem: I need only combinations with 100 or less days difference.我的问题:我只需要相差 100 天或更少天数的组合。
Actually my code breaks the loop.实际上我的代码打破了循环。 I would like to cut and continue with the next combinations.
我想削减并继续下一个组合。 Is it possible?
是否可以?
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
Rather than filtering in your loop, pass the combination iterator to filter()
.不是在循环中过滤,而是将组合迭代器传递给
filter()
。 It's a little hard to use your data since you didn't provide an example of what you have, but here's a minimal example that hopefully will give you enough of an idea.使用您的数据有点困难,因为您没有提供您所拥有的示例,但这里有一个最小的示例,希望能给您提供足够的想法。
With filter()
you just give it a lambda function that returns True for the combinations you want and False for those you don't:使用
filter()
您只需给它一个 lambda 函数,该函数对于您想要的组合返回 True,对于您不需要的组合返回 False:
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])
Prints:印刷:
(0, 1, 2, 3, 4) 4
(0, 1, 2, 3, 5) 5
(0, 1, 2, 4, 5) 5
(0, 1, 3, 4, 5) 5
(0, 2, 3, 4, 5) 5
(1, 2, 3, 4, 5) 4
(1, 2, 3, 4, 6) 5
(1, 2, 3, 5, 6) 5
...
(4, 5, 7, 8, 9) 5
(4, 6, 7, 8, 9) 5
(5, 6, 7, 8, 9) 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.