我有一個字典串列,我想在保留一些資訊的同時洗掉重復項。
對于背景關系,這些是區塊鏈交易。資訊如下:
交易哈希,
NFT的ID,
交易價值(可以是買入、賣出或鑄造價格)。
在下面的原始串列中,每個操作都是分開的。但是,我意識到有些具有相同的哈希值,所以它們只是一個具有多個操作的交易(在這種情況下,在一個交易中鑄造 2 個 NFT)。因此,您的目標是擁有一個干凈的串列,其中僅包含單個交易(由其哈希標識)和多個 ID,如果在一個交易中有多個操作,則用逗號分隔,以及總價格。
original_list = [
{
'hash': '12345',
'ID': '355',
'price': 12
},
{
'hash': '12345',
'ID': '356',
'price': 12
},
{
'hash': '635',
'ID': '355',
'price': 30
},
{
'hash': '637',
'ID': '356',
'price': 35
}
]
這是我想要的最終結果:
clean_list = [
{
'hash': '12345',
'ID': '355, 356',
'price': 12
},
{
'hash': '635',
'ID': '355',
'price': 30
},
{
'hash': '637',
'ID': '356',
'price': 35
}
]
我怎樣才能做到這一點?
uj5u.com熱心網友回復:
你可以遍歷你的串列并創建一個新的字典來合并資料:
def exist_in_list[hash,lst]: #function that checks if the hash is already in the list and returns the index if it does
for i in range(len(lst)):
if lst[i]['hash']==hash:
return i
return -1
new_list = []
for dict in clean_list:
index = exist_in_list(dict['hash'],new_list):
if index<0:
new_list.append(dict)
else:
new_list[index]['ID'] = f", {dict['ID']}"
可能有一些小的語法錯誤,但邏輯是存在的。
您遍歷第一個串列,檢查字典是否在新串列中,如果不是,則添加它,如果是,則在其中添加新 ID。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/420227.html
標籤:
上一篇:給定的成績串列
