1 回答
TA贡献1809条经验 获得超8个赞
在这里有点冗长以帮助查看结构。绝对可以做一些很酷的 lambda 东西来解决这个问题,并使列表理解更加“pythonic”。但这里有一个快速的解决方案!
# Set up initial data
unmerged = [
{"id":"1", "name":"Alice", "age":"25", "languages":"German"},
{"id":"1", "name":"Alice", "age":"25", "languages":"French"},
{"id":"2", "name":"John", "age":"30", "languages":"English"},
{"id":"2", "name":"John", "age":"30", "languages":"Spanish"}]
# merge the data by your composite key of id-name-age
merged = {}
for entry in unmerged:
entry_id = entry['id']
entry_name = entry['name']
entry_age = entry['age']
entry_languages = entry['languages']
composite_key = entry_id + entry_name + entry_age
if composite_key in merged:
merged[composite_key]['languages'].append(entry_languages)
else:
merged[composite_key] = {
'id': entry_id,
'name': entry_name,
'age': entry_age,
'languages': [entry_languages]
}
# reconstruct your list with just your unique entries
cleaned = []
for key, value in merged.items():
print(key, value)
cleaned.append({
'id': value['id'],
'name': value['name'],
'age': value['age'],
'languages': ', '.join(value['languages']) # string join langauges by ", "
})
for clean in cleaned:
print(clean)
然后为您提供最终输出,其中清理的是您的合并条目列表:
{'id': '1', 'name': 'Alice', 'age': '25', 'languages': 'German, French'}
{'id': '2', 'name': 'John', 'age': '30', 'languages': 'English, Spanish'}
谢谢,如果这有帮助,请告诉我!
添加回答
举报