2015-03-13 109 views
0

我想从Python中的列表中提取所有的字符串组合。例如,在下面的代码中,['a','b','c']和['b','a','c']不是唯一的,而['a','b',' c']和['a','e','f']或['a','b','c']和['d','e','f']是唯一的。从Python中的列表中提取唯一的字符串组合

我试过将列表列表转换为元组列表并使用集合来比较元素,但所有元素仍然被返回。

combos = [['a', 'b', 'c'], ['c', 'b', 'a'], ['d', 'e', 'f'], ['c', 'a', 'b'], ['c', 'f', 'b']] 

# converting list of list to list of tuples, so they can be converted into a set 
combos = [tuple(item) for item in combos] 
combos = set(combos) 

grouping_list = set() 
for combination in combos: 
    if combination not in grouping_list: 
     grouping_list.add(combination) 
## 

print grouping_list 
>>> set([('a', 'b', 'c'), ('c', 'a', 'b'), ('d', 'e', 'f'), ('c', 'b', 'a'), ('c', 'f', 'b')]) 

回答

2

如何排序,(和使用计数器)?

from collections import Counter 

combos = [['a', 'b', 'c'], ['c', 'b', 'a'], ['d', 'e', 'f'], ['c', 'a', 'b'], ['c', 'f', 'b']] 
combos = Counter(tuple(sorted(item)) for item in combos) 
print(combos) 

回报:

Counter({('a', 'b', 'c'): 3, ('d', 'e', 'f'): 1, ('b', 'c', 'f'): 1}) 

编辑:我不知道如果我正确理解你的问题。您可以使用Counter来计数发生次数,或者如果您只对结果集中的项目感兴趣,而不是其唯一性,则可以使用计数器对发生次数进行计数。

喜欢的东西:

combos = set(tuple(sorted(item)) for item in combos) 

只是返回

set([('a', 'b', 'c'), ('d', 'e', 'f'), ('b', 'c', 'f')]) 
+0

谢谢!是的,在我进行比较之前应该考虑分类。 – Bryan 2015-03-13 14:24:08

1
>>> set(tuple(set(combo)) for combo in combos) 
{('a', 'c', 'b'), ('c', 'b', 'f'), ('e', 'd', 'f')} 

简单,但如果我们在组合相同的元素,它会返回错误的答案。然后,排序是其他人建议的方式。

+1

您可以在这里保存几个字节:'set(frozenset(combo)for combo in combos)' – georg 2015-03-13 14:28:42

+0

@georg right,thanks for pointing! – 2015-03-13 14:29:26

0

如何:

combos = [['a', 'b', 'c'], ['c', 'b', 'a'], ['d', 'e', 'f'], ['c', 'a', 'b'], ['c', 'f', 'b']] 
print [list(y) for y in set([''.join(sorted(c)) for c in combos])] 
相关问题