【发布时间】:2018-08-20 16:23:12
【问题描述】:
我是 Python 新手,我正在尝试在脚本中解决这个问题。
我有 2 个字典列表,如下所示:
en_list = [{'time': 840, 'text': "I want to introduce you to some\nvery wise kids that I've known,"},
{'time': 5480, 'text': 'but first I want\nto introduce you to a camel.'},
{'time': 8720, 'text': 'This is Cassie, a therapy camel\nvisiting one of our young patients'},
{'time': 13000, 'text': 'in her room,'},
{'time': 14920, 'text': 'which is pretty magical.'}]
fr_list = [{'time': 840, 'text': "Je veux vous présenter certains enfants\ntrès sages que j'ai rencontrés,"},
{'time': 5480, 'text': 'mais je veux commencer\npar vous présenter un chameau.'},
{'time': 8720, 'text': 'Voici Cassie, un chameau thérapeutique qui\nrend visite à une de nos jeunes patients'},
{'time': 14920, 'text': 'ce qui est plutôt magique.'}]
我想创建一个新列表,其中仅包含“时间”键的匹配值。
我想出了这个,但显然它没有考虑时间键,尽管如果两个列表具有相同数量的字典,它就可以正常工作。
for i, m in enumerate(zip(en_list, fr_list), start=1):
print(i, m[0], "=", m[1])
这会打印出以下内容:
1 {'time': 840, 'text': "I want to introduce you to some\nvery wise kids that I've known,"} = {'time': 840, 'text': "Je veux vous présenter certains enfants\ntrès sages que j'ai rencontrés,"}
2 {'time': 5480, 'text': 'but first I want\nto introduce you to a camel.'} = {'time': 5480, 'text': 'mais je veux commencer\npar vous présenter un chameau.'}
3 {'time': 8720, 'text': 'This is Cassie, a therapy camel\nvisiting one of our young patients'} = {'time': 8720, 'text': 'Voici Cassie, un chameau thérapeutique qui\nrend visite à une de nos jeunes patients'}
4 {'time': 13000, 'text': 'in her room,'} = {'time': 14920, 'text': 'ce qui est plutôt magique.'}
如您所见,尽管英文列表具有相同时间的正确文本,但它错误地将带有'time': 13000 的英语映射到带有'time': 14920 的法语,但上面的代码忽略了它。
所需的输出应包括所有具有“时间”键匹配值的项目,并忽略不匹配的项目。我怎样才能做到这一点?
提前感谢您的支持!
【问题讨论】:
-
您的代码根本没有检查
time的值;相反,您只匹配列表中的物理位置。您必须至少 try 匹配time值。如果遇到困难,请在线搜索具有相同键的 dict 条目中的解决方案。
标签: python list dictionary merge