簡體   English   中英

查找兩個詞典列表中的常見成員

[英]Find common members that are in two lists of dictionaries

這可能是重復的,但我能找到的最接近的是比較2個列表,其中包含python中具有唯一鍵的字典,這對我來說不起作用。

所以我有兩個詞典列表。

y = [{'a': 3, 'b': 4, 'c': 5}, {'a': 1, 'b': 2, 'c': 3}]
y = [{'a': 4, 'b': 5, 'c': 6}, {'a': 1, 'b': 2, 'c': 3}]

如何比較這兩個列表,以便我的比較結果在兩個列表的交集處。 我無法將其轉換為設置,因為它表示不可用類型(字典)

你的問題和它的標題似乎相互矛盾。

兩個列表的交集將是兩個列表的共同元素。 問題標題請求不在兩個列表中的元素。 你想要的是哪一個?

對於交集,它不是非常有效(在時間上是O(n ^ 2)),但是這個列表理解將會這樣做:

>>> a = [{'a': 3, 'b': 4, 'c': 5}, {'a': 1, 'b': 2, 'c': 3}]
>>> b = [{'a': 4, 'b': 5, 'c': 6}, {'a': 1, 'b': 2, 'c': 3}]
>>> [d for d in a if d in b]
[{'a': 1, 'b': 2, 'c': 3}]
y1 = [{'a': 3, 'b': 4, 'c': 5}, {'a': 1, 'b': 2, 'c': 3}]
y2 = [{'a': 4, 'b': 5, 'c': 6}, {'a': 1, 'b': 2, 'c': 3}]
print [x for x in y1 if x in y2] # prints [{'a': 1, 'c': 3, 'b': 2}]

dict(或列表)不可清除,但是,元組是。 您可以將dicts列表轉換為一組元組。 執行交集然后轉換回來

轉換為一組元組的代碼

y_tupleset = set(tuple(sorted(d.items())) for d in y)

將相交的元組集轉換回dicts的代碼

y_dictlist = [dict(it) for it in list(y_tupleset)]

因此,完整的代碼將是:

y0 = [{'a': 3, 'b': 4, 'c': 5}, {'a': 1, 'b': 2, 'c': 3}]
y1 = [{'a': 4, 'b': 5, 'c': 6}, {'a': 1, 'b': 2, 'c': 3}]

y0_tupleset = set(tuple(sorted(d.items())) for d in y0)
y1_tupleset = set(tuple(sorted(d.items())) for d in y1)
y_inter = y0_tupleset.intersection(y1_tupleset)
y_inter_dictlist = [dict(it) for it in list(y_inter)]

print(y_inter_dictlist)
# prints the following line
[{'a': 1, 'c': 3, 'b': 2}]

編輯: d.items()在python3上有效,對於python2,它應該用d.iteritems()替換

選擇你的毒葯:

y1 = [{'a': 3, 'b': 4, 'c': 5}, {'a': 1, 'b': 2, 'c': 3}]
y2 = [{'a': 4, 'b': 5, 'c': 6}, {'a': 1, 'b': 2, 'c': 3}]
y3 = [{'a': 1, 'b': 2, 'c': 3}, {'a': 4, 'b': 2, 'c': 6}]

# Returns a list of keys that are in both dictionaries
def intersect_keys(d1, d2):
    return [k for k in d1 if k in d2]

# Returns a list of values that are in both dictionaries
def intersect_vals(d1, d2):
    return [v for v in d1.itervalues() if v in d2.itervalues()]

# Returns a list of (key,value) pairs that are in both dictionaries
def intersect_pairs(d1, d2):
    return [(k,v) for (k,v) in d1.iteritems() if k in d2 and d2[k] == v]


print(intersect_keys(*y1))      # ['a', 'c', 'b']
print(intersect_vals(*y1))      # [3]
print(intersect_pairs(*y1))     # []

print(intersect_keys(*y2))      # ['a', 'c', 'b']
print(intersect_vals(*y2))      # []
print(intersect_pairs(*y2))     # []

print(intersect_keys(*y3))      # ['a', 'c', 'b']
print(intersect_vals(*y3))      # [2]
print(intersect_pairs(*y3))     # [('b', 2)]

注意:這些例子比較了y*列表的兩個元素,這就是我如何解釋你的問題。 你當然可以使用類似的東西:

print(intersect_pairs(y1[0], y2[0]))

要計算交叉點, y1y2列表中的第一個字典。

暫無
暫無

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

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