簡體   English   中英

如果列表中的項目相同,如何合並列表中的項目,如果項目不相同,則在 Python 中追加

[英]How to merge the items of list if they are same and append if items are not same in Python

我有一個包含以下dict數據的列表tags

tags = [ {'Time': 1, 'Name': 'John'} ]

我從函數中獲取tags值。 有時收到的值具有相同的Name因此在這種情況下,我需要簡單地獲取其Time值並更新列表。 例如,如果收到以下數據:

tags = [ {'Time': 4, 'Name': 'John'} ]

在這種情況下,由於Name是相同的,所以我將簡單地獲取Time值並更新tags列表,因此輸出將是:

output = [ {'Time': 4, 'Name': 'John'} ]

時間已從 1 更改為 4。但是假設收到了一個新Name ,例如以下:

tags = [ {'Time': 10, 'Name': 'John'}, {'Time': 6, 'Name': 'Karan'} ]

所以在這種情況下, John時間將被更新, Karan時間數據將被附加到列表中,因此輸出將是

output = [ {'Time': 10, 'Name': 'John'}, {'Time': 6, 'Name': 'Karan'} ]

因此,對於 John,我們更新了時間並添加了 Karan 數據。

我有output_tags作為dict ,其中有一個tags作為list 我正在做以下事情:

output_tags['Tags'].clear()
for tag in tags:
    output_tags['Tags'].append(tag)

現在上面的代碼正在清除我們在output_tags['Tags']任何數據,然后簡單地附加所有數據。 因此,通過這種方式,我們將更新相同的Name時間並附加收到的任何新Name

但是使用此代碼,我正在清除我以前擁有的任何數據。 例如,前一段時間我收到了Ellis數據,但現在我沒有收到Ellis數據。 我仍然需要保留Ellis數據,但它已被清除。 有沒有其他方法可以解決這個問題。 請幫忙。 謝謝

您可以合並兩個標簽列表:

from collections import defaultdict

tags = [ {'Time': 10, 'Name': 'John'}, {'Time': 6, 'Name': 'Karan'} ]
new_tags = [ {'Time': 30, 'Name': 'Bob'}, {'Time': 40, 'Name': 'Karan'} ]

d = defaultdict(dict)
# using defaultdict(dict), whatever the key your using, it will be initiated with a dict : `d['random_key'] == {}` is True

# we fill d with all tags and new_tags using `Name` as key
for list_ in (tags, new_tags):
    for obj in list_:
        # if `obj['Name']` has already been set, it is updated
        # otherwise it is added
        d[obj['Name']].update(obj)

# display only values and make it a list
results = list(d.values())

print(results)

# [{'Time': 10, 'Name': 'John'}, {'Time': 40, 'Name': 'Karan'}, {'Time': 30, 'Name': 'Bob'}]

暫無
暫無

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

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