简体   繁体   English

获取列表项及其名称的所有组合

[英]Get all combinations of list items with their names

I want to get all the combinations of a list of values.我想获取值列表的所有组合。 I was able to do that via this code:我可以通过以下代码做到这一点:

list_of_all_features_to_combine = [name1, name2, name3]
    
    
import itertools
all_combinations = []
for L in range(0, len(list_of_all_features_to_combine)+1):
    for subset in itertools.combinations(list_of_all_features_to_combine, L):        
         all_combinations.append(subset)

I print one combination as follows:我打印一种组合如下:

print(all_combinations[0])

Of course, I only get the values.当然,我只得到值。

My problem is that I want to know "which" items are combined, so I need the variable names.我的问题是我想知道组合了“哪些”项目,所以我需要变量名。 The only way to do that, that I can imagine, is to have a list of dictionaries with the names as string and then combine these, but I'm sure, that there is a simpler and more elegant way of doing that.我可以想象,这样做的唯一方法是拥有一个名称为字符串的字典列表,然后将它们组合起来,但我敢肯定,有一种更简单、更优雅的方法来做到这一点。 Maybe some method of how to retrieve the variable names, such that I get an output like name1, name2: (1,2)也许一些如何检索变量名称的方法,这样我得到一个 output 像name1, name2: (1,2)

Perhaps this is what you're looking for:也许这就是您正在寻找的:

from itertools import combinations

name1, name2, name3 = 10,20,30
names = ["name1", "name2", "name3"]
list_of_all_features_to_combine = [name1, name2, name3]

my_globals = globals()
name_combs = [subset for L in range(len(names)+1) 
              for subset in combinations(names,L)]
result = {t:tuple(my_globals[var] for var in t) for t in name_combs }

The result looks like this:结果如下所示:

print (result)

{(): (),
 ('name1',): (10,),
 ('name2',): (20,),
 ('name3',): (30,),
 ('name1', 'name2'): (10, 20),
 ('name1', 'name3'): (10, 30),
 ('name2', 'name3'): (20, 30),
 ('name1', 'name2', 'name3'): (10, 20, 30)}

To access only the combinations of values:要仅访问值的组合:

print (list(result.values()))

[(), (10,), (20,), (30,), (10, 20), (10, 30), (20, 30), (10, 20, 30)]

To access only the combinations of names:要仅访问名称组合:

print (list(result.keys()))
[(), ('name1',), ('name2',), ('name3',), ('name1', 'name2'), ('name1', 'name3'), ('name2', 'name3'), ('name1', 'name2', 'name3')]

I am not sure if I got you correctly, but is this what you looking for?我不确定我是否正确理解了您,但这就是您要找的吗? Or maybe part of it?或者可能是其中的一部分?

l = ["name1", "name2", "name3"] 
x = [x for x in itertools.permutations(l, r=3)]
for i in enumerate(x):
    print(i)

If you can explain maybe more specific?如果你能解释得更具体一点?

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

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