2013-03-02 64 views
2

我想要計算子列表元素的唯一實例的數量,然後將每個唯一元素寫入新列表,並將子實例附加到子列表中。 list_1中的每個子列表都只有兩個元素,順序無關緊要。python中的子列表元素的計數和追加

這樣:

list_1 = [[a, b], [a, c], [a, c], [a, c], [b, e], [d, q], [d, q]] 

變爲:

new_list = [[a, b, 1], [a, c, 3], [b, e, 1], [d, q, 2]] 

我在想,我需要使用集,但我很欣賞的人指着我在正確的方向。

+1

你能闡述'[A,C,3],[A,C ,1]'? – NPE 2013-03-02 16:33:27

+0

此外,'list_1'的相同元素保證連續? – NPE 2013-03-02 16:34:19

+0

這些必須是list()或者tuple()嗎? – 2013-03-02 16:37:15

回答

1

如果相同的子列表是連續的:

from itertools import groupby 

new_list = [sublist + [sum(1 for _ in g)] for sublist, g in groupby(list_1)] 
# -> [['a', 'b', 1], ['a', 'c', 3], ['b', 'e', 1], ['d', 'q', 2]] 
+0

謝謝 - 這對我來說是最簡單的解決方案 – spatialaustin 2013-03-11 23:53:39

6

你想看看collections.Counter(); Counter物件爲多套(亦稱袋子);他們將鍵映射到他們的計數。

得把你的子表到元組是可作爲鑰匙,但:

from collections import Counter 

counts = Counter(tuple(e) for e in list_1) 

new_list = [list(e) + [count] for e, count in counts.most_common()] 

,讓你通過計數排序的new_list(降序):

>>> from collections import Counter 
>>> list_1 = [['a', 'b'], ['a', 'c'], ['a', 'c'], ['a', 'c'], ['b', 'e'], ['d', 'q'], ['d', 'q']] 
>>> counts = Counter(tuple(e) for e in list_1) 
>>> [list(e) + [count] for e, count in counts.most_common()] 
[['a', 'c', 3], ['d', 'q', 2], ['a', 'b', 1], ['b', 'e', 1]] 

如果您發生總是連續的,那麼你也可以使用itertools.groupby()

from itertools import groupby 

def counted_groups(it): 
    for entry, group in groupby(it, key=lambda x: x): 
     yield entry + [sum(1 for _ in group)] 

new_list = [entry for entry in counted_groups(list_1)] 

我在這裏使用了一個單獨的生成器函數,但是可以將循環內聯到列表理解中。

這給:

>>> from itertools import groupby 
>>> def counted_groups(it): 
...  for entry, group in groupby(it, key=lambda x: x): 
...   yield entry + [sum(1 for _ in group)] 
... 
>>> [entry for entry in counted_groups(list_1)] 
[['a', 'b', 1], ['a', 'c', 3], ['b', 'e', 1], ['d', 'q', 2]] 

,並保留原始排序。

0

一個比特的 '輪的房屋' 溶液

list_1 = [['a', 'b'], ['a', 'c'], ['a', 'c'], ['a', 'c'], ['b', 'e'], ['d', 'q'], ['d', 'q']] 
new_dict={} 
new_list=[] 
for l in list_1: 
    if tuple(l) in new_dict: 
     new_dict[tuple(l)] += 1 
    else: 
     new_dict[tuple(l)] = 1 
for key in new_dict: 
    entry = list(key) 
    entry.append(new_dict[key]) 
    new_list.append(entry) 
print new_list