【发布时间】:2020-06-26 06:34:17
【问题描述】:
我正在尝试遍历字典数组,比较它们之间的每个值,然后将结果附加到字典中。
例如,如果我们有以下数组:
epidemics = [{"Disease": "B", "year": "1980"},
{"Disease": "C", "year": "1975"},
{"Disease": "B", "year": "1996"},
{"Disease": "E", "year": "2000"},
{"Disease": "B", "year": "2020"}]
如果其他年份也发生了同一种疾病的流行,我想要达到的结果是:
epidemics = [{"Disease": "B", "year": "1980", "occurredIn": ["1996", "2020"]},
{"Disease": "C", "year": "1975"},
{"Disease": "B", "year": "1996", "occurredIn": ["1980", "2020"]},
{"Disease": "E", "year": "2000"},
{"Disease": "B", "year": "2020", "occurredIn": ["1980", "1996"]}]
这是我到目前为止的地方:
for index, a in enumerate(epidemics):
v_b = []
for b in epidemics[index+1:]:
if a['Disease'] == b['Disease']:
v_b.append(b["year"])
a['occurredIn'] = v_b
它打印我:
[{'Disease': 'B', 'year': '1980', 'occurredIn': ['1996', '2020']},
{'Disease': 'C', 'year': '1975'},
{'Disease': 'B', 'year': '1996', 'occurredIn': ['2020']},
{'Disease': 'E', 'year': '2000'},
{'Disease': 'B', 'year': '2020'}]
提前致谢
【问题讨论】:
-
如果可以的话,我不认为你想要的结果实际上是一个好的结构。为什么不只存储疾病 B 一次,将所有年份都放在同一个地方?如果您每年需要一些东西,您总是可以相应地访问该信息。这个结构是一个简单的字典,键是疾病,值是年份列表
-
@ParitoshSingh 感谢您的提示....此数据只是一个示例,我正在使用的数据更加可靠。无论如何,我会记住这一点。欢呼
标签: python dictionary append compare