2016-11-28 97 views
1

我有3名名單:產品與descreasing值

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 

有一個簡單的這樣做的方式還是應該與列表理解和條件?

回答

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 
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 

我在這裏找到這裏:

Determine if a list is in descending order

0

如果你不想使用列表理解爲某種原因:

def decreasing(l): 
    return all(a >= b for a, b in zip(l[:-1], l[1:])) 


filter(decreasing, product(a, b, c)) 
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