2015-03-13 111 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])] 
相關問題