Skip to main content
 首页 » 编程设计

python之值(value)递减的产品

2025年05月04日28mengfanrong

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

有没有一种简单的方法可以做到这一点,还是我应该使用列表理解和条件?

请您参考如下方法:

您可以通过遍历 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