我有3个名单:
a = [10, 9, 8, 7, 6]
b = [8, 7, 6, 5, 4, 3]
c = [6, 5, 4, 3, 2]
我需要获得itertools.product()
获得的所有排列,但只有在值减少的情况下才能获得:
[10, 8, 6] # is good
[6, 8, 4] # is not good, since 8 > 6
有一种简单的方法可以做到这一点,还是应该使用列表理解和条件?
答案 0 :(得分:3)
你可以通过遍历itertools.product
迭代器并仅提取那些反向排序的返回项来实现列表推导:
[item for item in product(a,b,c) if sorted(item, reverse = True) == list(item)]
示例:
from itertools import product
a = [10,9,8,7,6]
b = [8, 7, 6, 5, 4, 3]
c = [6, 5, 4, 3, 2]
[item for item in product(a,b,c) if sorted(item, reverse = True) == list(item)]
# [(10, 8, 6), (10, 8, 5), (10, 8, 4), (10, 8, 3), (10, 8, 2) ...continues
答案 1 :(得分:2)
您可以参考以下没有列表推导的代码:
from itertools import product
a = [10, 9, 8, 7, 6]
b = [8, 7, 6, 5, 4, 3]
c = [6, 5, 4, 3, 2]
for result in product(a,b,c):
if sorted(result, reverse = True) == list(result):
print result
答案 2 :(得分:0)
这是一个简单的单行解决方案
>>> mylist = [10, 9, 8, 7, 6]
>>> all(earlier >= later for earlier, later in zip(mylist, mylist[1:]))
True
>>> mylist = [10, 9, 7, 8, 6]
>>> all(earlier >= later for earlier, later in zip(mylist, mylist[1:]))
False
我在这里找到了这个:
答案 3 :(得分:0)
如果您由于某种原因不想使用列表推导:
def decreasing(l):
return all(a >= b for a, b in zip(l[:-1], l[1:]))
filter(decreasing, product(a, b, c))