简体   繁体   English

Python - 如何从嵌套列表中获取所有可能的组合

[英]Python - How to get all possible combinations from nested list

I have a nested list like this :我有一个这样的嵌套列表:

values = [['DNO', 0.2], ['Equinor', 0.4], ['Petoro', 0.2], ['Total', 0.2]]

How to get all possible combinations of elements that will have a sum(2nd element of each sub list) greater than 0.5?如何获得总和(每个子列表的第二个元素)大于 0.5 的元素的所有可能组合?

This is what I am using :这就是我正在使用的:

def getCombinations(values, min_len):
    combo = "\n"
    numbers = []
    doc = {}
    for val in values:
        doc[val[0]] = val[1]
        numbers.append(val[1])

    result = [seq for i in range(len(numbers), 0, -1) for seq in itertools.combinations(numbers, i) if sum(seq) >= 0.5]
    temp = doc.copy()

    for r in result:
        doc = temp.copy()
        if len(r) >= min_len:
            for rr in r:
                combo = combo + get_key(doc, rr) + " "

                doc.pop(get_key(doc, rr))
            combo = combo + "\n"
    return combo

My algorithm have some problem when there are multiple values like 0.2 in above list.当上面列表中有多个值(如 0.2)时,我的算法会出现一些问题。

Currently it is returning this with min_length=3 :目前它返回min_length=3

Total Equinor Petoro DNO
Total Equinor Petoro 
Total Equinor Petoro 
Total Petoro DNO 
Equinor Total Petoro 

The following should work:以下应该工作:

import itertools  
result=[] 
for k in range(2,len(values)+1):
    temp=[tuple(x[0] for x in i) for i in list(itertools.combinations(values,k))if sum([p[1] for p in i]) >0.5]
    result.append(temp)
result=sum(result, [])
print(result)

Output:输出:

[('DNO', 'Equinor'), ('Equinor', 'Petoro'), ('Equinor', 'Total'), ('DNO', 'Equinor', 'Petoro'), ('DNO', 'Equinor', 'Total'), ('DNO', 'Petoro', 'Total'), ('Equinor', 'Petoro', 'Total'), ('DNO', 'Equinor', 'Petoro', 'Total')]

You can use a list comprehension like this:您可以使用这样的列表理解:

Explanation:解释:

  • The first for defines the length of the combinations.第一个for定义了组合的长度。 Every length from 2 to the length of values is used.使用从 2 到values长度的每个长度。
  • The second for creates the actual combinations第二个for创建实际组合
  • The if uses a generator method to sum the numbers of the items if使用生成器方法对项目的数量求和
from itertools import combinations

combis = [
    item
    for length in range(2, len(values)+1)
    for item in combinations(values, length)
    if sum(i[1] for i in item) >= 0.5
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM