我正在学习Python。我知道如何在JavaScript中做到这一点,但目前我缺乏语法知识,也找不到告诉我如何做到这一点的例子。
我有以下对象数组:
john_williams_compositions = [
{"year": 1973, "Title": "The Poseidon Adventure", "type": "Best Orignal Score", "status": "nominated"},
{"year": 1974, "Title": "Cinderella Liberty", "type": "Best Original Score", "status": "nominated"},
{"year": 1974, "Title": "Tom Sawyer", "type": "Best Original Score", "status": "nominated"},
{"year": 1975, "Title": "Earthquake", "type": "Best Original Score", "status": "nominated"},
{"year": 1976, "Title": "Jaws", "type": "Best Original Score", "status": "Won"},
{"year": 1978, "Title": "Close Encounters of the Third Kind", "type": "Best Original Score", "status": "nominated"},
{"year": 1978, "Title": "Star Wars: Episode IV - A New Hope", "type": "Best Original Score", "status": "Won"},
{"year": 1979, "Title": "Superman", "type": "Best Original Score", "status": "nominated"},
{"year": 1981, "Title": "Star WArs: Episode V - The Empire Strikes Back", "type": "Best Original Score", "status": "nominated"},
{"year": 1983, "Title": "E.T. the Extra Terrestrial", "type": "Best Original Score", "status": "Won"},
{"year": 1983, "Title": "If We Were in Love", "type": "Best Original Song", "status": "nominated"},
{"year": 1985, "Title": "The River", "type": "Best Original Score", "status": "nominated"},
{"year": 1988, "Title": "Empire of the Sun", "type": "Best Original Score", "status": "nominated"}
]
现在我想在一个新数组中获取所有状态为"Won"
的对象。
我自己想出来的:
def won(list):
result = []
for x in list:
if x.status == "Won":
result.append[i]
return result
print(won(john_williams_compositions))
有人能帮我启动这个吗?
4条答案
按热度按时间zlwx9yxi1#
x
是dict
。与Javascript不同(我认为),在dict
中访问给定键的值和访问属性的值之间存在语法差异。您的循环需要前者:
wgx48brx2#
您可以通过列表理解非常容易地做到这一点:
或者,您可以使用
filter()
函数:b4qexyjb3#
因为你是一个初学者,列表理解对你来说可能不是很容易,这里有一个简单的实现:
7gs2gvoe4#
你只需要遍历字典列表,然后选择那些
status
键等于Won
的字典。也许最好写一个函数来处理任何状态值。就像这样:
输出:
注意:
get_by_status()
可以在一行代码中实现为列表解析。由于OP显然是初学者,因此为了清晰起见,以这种方式编写。