【发布时间】:2021-09-14 12:31:43
【问题描述】:
我正在寻找将多个列表组合成一个列表的解决方案,以便稍后转换为表格。所有列表都有相同的元素,其中一些有唯一的项目。
person1 = [['Name','Alex'], ['Gender','M'], ['Age', 30]]
person2 = [['Name','Anna'], ['Gender','F'], ['Phone','1234567'],['Age', 25]]
person3 = [['Name','Fred'], ['Gender','M'], ['Age', 33], ['Passport', '987654']]
我想将其转换为列表/表格如下:
# Name Alex Anna Fred
# Gender M F M
# Phone #N/A 1234567 #N/A
# Age 30 25 33
# Passport #N/A #N/A 987654
我尝试使用 dict,但是如果 key 已经存在,则无法创建添加数据的函数:
combined = {}
for item in person1:
if item[0] in combined:
# How to add data, if key already exists in dict ?
print('Exists')
else:
combined[item[0]] = item[1]
for item in person2:
if item[0] in combined:
# How to add data, if key already exists in dict ?
print('Exists')
else:
combined[item[0]] = item[1]
for item in person3:
if item[0] in combined:
# How to add data, if key already exists in dict ?
print('Exists')
else:
combined[item[0]] = item[1]
print(combined)
# Current output
# {'Name': 'Alex', 'Gender': 'M', 'Age': 30, 'Phone': '1234567', 'Passport': '987654'}
如果有人可以建议如何制作,将不胜感激。
【问题讨论】:
-
该表结构不是作为数据类型存在的东西。你想要的是一个字典列表,或者一些人类的列表,在这里会更好
-
谢谢。我不认为我可以在这里使用类(如果我理解正确的话),因为我不知道所有可能的字段来定义它们。例如,下一个数据列表可以包含“国家”字段,如果没有在类中描述,则不会被处理。
-
是的,如果您的字段是动态的,那么 dicts 列表就是 2ay
标签: python python-3.x list dictionary