簡體   English   中英

如何從列表列表中識別所有相同的列表?

[英]How to identify all identical lists from a list of lists?

嗨! 我有一個列表列表,當子列表的第一個元素相等時,我需要添加其中的第二個元素並打印結果。 我已經考慮了很久,但我似乎無法弄清楚如何做到這一點。 這是我的問題的一個例子:

num_list = [[1, 2], [3, 4], [1, 2], [3, 4], [3, 4]]

# 0th and 2nd sublists both have 1 as their first element.
# sum = 2 + 2. print out 4.

# all the remaining sublists have 3 as their first element.
# sum = 4 + 4 + 4. print out 12. 

非常感謝你!

PS:我知道這種映射最好用字典來完成,但這只是我問題的簡化版本。 我的實際程序有超過2個值的子列表,我需要比較多於1個需要相等的值。

你可以使用defaultdict

from collections import defaultdict

num_list = [[1, 2], [3, 4], [1, 2], [3, 4], [3, 4]]

d = defaultdict(int)

for item in num_list:
    d[item[0]] += item[1]

結果是:

>>> d
defaultdict(<type 'int'>, {1: 4, 3: 12})

您仍然可以使用dictonary執行此任務。 使用元組作為鍵:

>>> d = {(1,1): (2,2), (3,3): (4,4)}
>>> d
{(1, 1): (2, 2), (3, 3): (4, 4)}
>>> d[(1,1)]
(2, 2)

您可能還想了解Counter類。 如果你的元素更復雜,我建議將它們包裝在對象中並實現__add__方法來自定義它們的__add__方式。

from collections import Counter
c = Counter()
c[(1,1)] = 10
c[(2,2)] = 10
c[(1,1)] += 1

c2 = Counter()
c2[(2,2)] = 4
c2[(2,3)] = 5

這使:

>>> c 
Counter({(1, 1): 11, (2, 2): 10})
>>> c + c2
Counter({(2, 2): 14, (1, 1): 11, (2, 3): 5})

請注意,您不能將列表用作鍵,因為列表是可變的,因此無法哈希。 您必須使用元組。

使用標准dict()

num_list = [[1, 2], [3, 4], [1, 2], [3, 4], [3, 4]]

d = dict()
for e in num_list:
    #get() checks if key exists, if not - returns 0        
    d[e[0]] = d.get(e[0], 0) + e[1]

print(d)

它打印:

{1: 4, 3: 12}

您似乎沒有足夠准確地描述您的問題。
你的真正問題只能通過你對@Blender的問題和答案的評論來理解。 他對這個問題的好解決方案不能立即解決我理解的問題,但是差不多。

這是一種擴展以滿足您需求的方法:

# some toy example data - I understand you want the first 2 sub_list
# to be "merged" because BOTH strings in pos 0 and 2 match
data = [['42x120x1800', 50, '50x90x800', 60],
        ['42x120x1800', 8, '50x90x800', 10],
        ['2x10x800', 5, '5x9x80', 6]]


from collections import defaultdict

# I'm using a lambda to initialize the items of the dict
# to a two-element list of zeros
d = defaultdict(lambda :[0, 0])
for sub_list in data:
    key = (sub_list[0], sub_list[2])
    d[key][0] += sub_list[1]
    d[key][1] += sub_list[3]

for key in d:
    print key, d[key]   
# ('2x10x800', '5x9x80') [5, 6]
# ('42x120x1800', '50x90x800') [58, 70]

如果您想返回數據的初始表示:

new_data = [[key[0], val[0], key[1], val[1]] for key, val in d.iteritems()]
# [['2x10x800', 5, '5x9x80', 6], ['42x120x1800', 58, '50x90x800', 70]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM