Python 具有递减值的产品
我有三个清单:Python 具有递减值的产品,python,python-2.7,list-comprehension,itertools,Python,Python 2.7,List Comprehension,Itertools,我有三个清单: 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 有一种简单的方法吗?或者我应该使用列表理解和条件吗?您可以使用列表理解通过在Itertools.product迭代器上循环并仅提取按相反顺序排
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
有一种简单的方法吗?或者我应该使用列表理解和条件吗?您可以使用列表理解通过在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
您可以通过列表理解来做到这一点,方法是在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
这是一个简单的单线解决方案
>>> 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
我在这里找到了这个:
这是一个简单的单线解决方案
>>> 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
我在这里找到了这个:
如果出于某种原因不想使用列表理解:
def decreasing(l):
return all(a >= b for a, b in zip(l[:-1], l[1:]))
filter(decreasing, product(a, b, c))
如果出于某种原因不想使用列表理解:
def decreasing(l):
return all(a >= b for a, b in zip(l[:-1], l[1:]))
filter(decreasing, product(a, b, c))
您可以引用以下没有列表理解的代码:
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
您可以引用以下没有列表理解的代码:
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