我有两个列表,其中 1 存储几个名人的信息,另一个列表存储与这些演员有关的奖项信息。
我试图解决的问题是将这两个列表组合成一个,其中奖励信息成为一个属性,本质上是一个奖励列表。是的,这很容易实现。
for actor in actor_info:
for award in award_list:
if actor['personid'] == award['personid']:
if not actor.get('awards', False):
actor.update({'awards':[]})
actor['awards'].append(award)
但是,如果您观察上面的代码,它会重复len(actor_info) * len(award_list)
多次,这不是一个优雅的解决方案。这个问题是否有其他观点,执行周期要少得多。
笔记:
为了更清楚地解释这个问题,我在下面描述了正在使用的数据结构。actor_info 和award_info 列表中的每个元素本质上都是一个字典。
actor_info = []
d = {}
d['personid'] = 1210
d['firstname'] = 'Robert , Jr'
d['lastname'] = 'Downey'
d['birthplace'] = 'manhattan, NY'
d1 = {}
d1['personid'] = 2842
d1['firstname'] = 'Brad'
d1['lastname'] = 'Pitt'
d1['birthplace'] = 'Shawnee, OK'
d2 = {}
d2['personid'] = 361
d2['fname'] = 'Cate'
d2['lname'] = 'Blanchett'
d2['birthplace'] = 'Melbournce, Victoria'
d3 = {}
d3['personid'] = 261
d3['fname'] = 'Meg'
d3['lname'] = 'Ryan'
d3['birthplace'] = 'Melbournce, Victoria'
actor_info.append(d)
actor_info.append(d1)
actor_info.append(d2)
actor_info.append(d3)
获奖信息:
k = {}
k['year'] = '1992'
k['won'] = 'NO'
k['category'] = 'Best Actor'
k['name'] = 'Academy Award'
k['movie'] = 'Chaplin'
k['personid'] = 1210
k1 = {}
k1['year'] = '2008'
k1['won'] = 'NO'
k1['category'] = 'Best Actor'
k1['name'] = 'Academy Award'
k1['movie'] = 'Tropic thunder'
k1['personid'] = 1210
k2 = {}
k2['year'] = '2008'
k2['won'] = 'NO'
k2['category'] = 'Best Actor'
k2['name'] = 'Academy Award'
k2['movie'] = 'The Curious Case of Benjamin Button'
k2['personid'] = 2842
k3 = {}
k3['year'] = '1989'
k3['won'] = 'yes'
k3['category'] = 'Best supporting Actress'
k3['name'] = 'Academy award'
k2['movie'] = 'Aviator'
k3['personid'] = 361
award_list = []
award_list.append(k)
award_list.append(k1)
award_list.append(k2)
award_list.append(k3)