我正在尝试编写一个python函数,它以电影标题作为键,以电影中的表演者列表作为值,然后返回一个新的dict,以表演者作为键,以电影中的表演者作为值。这段代码很接近,但每次运行都返回不同的结果
以下是原始函数调用:
movies = {"How to Be Single": ["Alison Brie", "Dakota Johnson",
"Rebel Wilson"],
"The Lego Movie": ["Will Arnett", "Elizabeth Banks",
"Alison Brie", "Will Ferrell"]}
print(stars,movies)
代码如下:
def stars(movies):
# create a new dictionary
films_dict= {}
performances_films = []
# for each movie actor, add as key to new_dict
for movie, actors in movies.items():
for actor in actors:
if not actor in films_dict.keys():
#print(actor)
performances_films = []
performances_films.append(movie)
films_dict[actor] = performances_films
else:
performances_films.append(movie)
films_dict[actor] = performances_films
return(films_dict)
以下是输出:
RUN 1
{'Rebel Wilson': ['How to Be Single'], 'Will Ferrell': ['The Lego
Movie'],
'Will Arnett': ['The Lego Movie'], 'Elizabeth Banks': ['The Lego Movie',
'The Lego Movie'], 'Alison Brie': ['The Lego Movie', 'The Lego Movie'],
'Dakota Johnson': ['How to Be Single']}
RUN 2
{'Will Arnett': ['The Lego Movie'], 'Dakota Johnson': ['How to Be Single'], 'Elizabeth Banks': ['The Lego Movie', 'The Lego Movie'], 'Rebel Wilson': ['How to Be Single'], 'Will Ferrell': ['The Lego Movie'], 'Alison Brie': ['The Lego Movie', 'The Lego Movie']}
我认为它要么在每次运行时以不同的顺序遍历dict项,要么从一次运行到下一次运行保存数据。不管怎样,我似乎都解决不了
我真的不明白你为什么要留着一张
performances_films
清单。您可以只使用前面在dict
本身中创建的那些以下是我认为可行的方法:
代码中的错误是
list
实例performances_films
从一个循环迭代持续到下一个循环迭代。这就是为什么(比如)Alison Brie把Lego电影列了两次,它本来应该是为另一个演员添加的,但是之前为Alison Brie创建的list
实例仍然占据了名称槽performances_films
。事实上,看起来多个参与者可能共享同一个list
实例如果在访问字典时使用“default value”概念,可以大大简化代码。这可以通过使用^{} 类来完成:
或者我更喜欢的方法是香草} 方法:
dict
和它的^{无论哪种方式,您都可以统一地对待每部新电影,而不必显式地测试演员先前的
filmography
成员资格印刷品:
相关问题 更多 >
编程相关推荐