我有問題,我有這樣的串列:
[{'id': 34, 'questionid': 5, 'text': 'yes', 'score': 1},
{'id': 10, 'questionid': 5, 'text': 'test answer updated', 'score': 2},
{'id': 20, 'questionid': 5, 'text': 'no', 'score': 0},
{'id': 35, 'questionid': 5, 'text': 'yes', 'score': 1}]
我想洗掉重復的“questionid”、“text”和“score”,例如在這種情況下我想要這樣的輸出:
[{'id': 34, 'questionid': 5, 'text': 'yes', 'score': 1},
{'id': 10, 'questionid': 5, 'text': 'test answer updated', 'score': 2},
{'id': 20, 'questionid': 5, 'text': 'no', 'score': 0}]
我怎樣才能在python中得到這個輸出?
uj5u.com熱心網友回復:
我們可以創建以“questionid”、“text”和“score”元組為鍵、以字典為值的字典,并使用此字典檢查以下中的重復值data:
from operator import itemgetter
out = {}
for d in data:
key = itemgetter("questionid", "text", "score")(d)
if key not in out:
out[key] = d
out = list(out.values())
輸出:
[{'id': 34, 'questionid': 5, 'text': 'yes', 'score': 1},
{'id': 10, 'questionid': 5, 'text': 'test answer updated', 'score': 2},
{'id': 20, 'questionid': 5, 'text': 'no', 'score': 0}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/439685.html
下一篇:關于C 單鏈表實作的問題
