在Python中迭代数值/键值对

huangapple go评论63阅读模式
英文:

Iterate on values/key pairs in Python

问题

Sure, here's the translated code part you requested:

我正在学习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))

希望这可以帮助你!

英文:

I'm learning Python. I know how to do this in JavaScript but I lack the syntax-knowledge at this very moment nor can I find examples that tell me how to do this.

I have the following Array of Objects:

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"}
]

Now I want to get all the objects with the status "Won" in a new array.

I came up with this myself:

def won(list):
result = []
for x in list:
if x.status == "Won":
result.append[i]
return result
print(won(john_williams_compositions))

Can anyone jumpstart me with this?

答案1

得分: 1

你可以很容易地使用列表推导来完成这个任务:

def won(lst):
    return [comp for comp in lst if comp['status'] == 'Won']

print(won(john_williams_compositions))

或者,作为另一种选择,你可以使用filter()函数

def won(lst):
    return list(filter(lambda comp: comp['status'] == 'Won', lst))

print(won(john_williams_compositions))
英文:

You can do this very easily with a list comprehension:

def won(lst):
return [comp for comp in lst if comp['status'] == 'Won']
print(won(john_williams_compositions))

Or, alternatively, you can use the filter() function:

def won(lst):
return list(filter(lambda comp: comp['status'] == 'Won', lst))
print(won(john_williams_compositions))

答案2

得分: 1

你只需要迭代列表(字典列表),然后选择其中status键等于Won的部分。

最好编写一个处理任何状态值的函数,类似这样:

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"}
]

def get_by_status(lst, status):
    result = []

    for d in lst:
        if d.get('status') == status:
            result.append(d)
            
    return result

print(get_by_status(john_williams_compositions, 'Won'))

输出:

{'year': 1976, 'Title': 'Jaws', 'type': 'Best Original Score', 'status': 'Won'}, {'year': 1978, 'Title': 'Star Wars: Episode IV - A New Hope', 'type': 'Best Original Score', 'status': 'Won'}, {'year': 1983, 'Title': 'E.T. the Extra Terrestrial', 'type': 'Best Original Score', 'status': 'Won'}]

注意: get_by_status() 可以以一行代码的形式作为列表推导式来实现。因为显然是初学者,所以以这种方式编写以提高清晰度。

def get_by_status(lst, status):
    return [d for d in lst if d.get('status') == status]
英文:

You just need to iterate over the list (of dictionaries) then select those where the status key is equal to Won.

Probably best to write a function that will handle any status value. Something like this:

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"}
    ]

def get_by_status(lst, status):
    result = []

    for d in lst:
        if d.get('status') == status:
            result.append(d)
            
    return result

print(get_by_status(john_williams_compositions, 'Won'))

Output:

{'year': 1976, 'Title': 'Jaws', 'type': 'Best Original Score', 'status': 'Won'}, {'year': 1978, 'Title': 'Star Wars: Episode IV - A New Hope', 'type': 'Best Original Score', 'status': 'Won'}, {'year': 1983, 'Title': 'E.T. the Extra Terrestrial', 'type': 'Best Original Score', 'status': 'Won'}]

Note: get_by_status() could be implemented as a list comprehension in one line of code. As OP is obviously a beginner, it's written this way for clarity.

def get_by_status(lst, status):
return [d for d in lst if d.get('status') == status]

答案3

得分: 1

这是一个简单的实现示例,因为你是初学者,列表推导可能看起来不太容易理解:

def won(list):
    result = []
    for x in list:
        if x['status'] == 'Won':
            print(x['status'])
            result.append(x)
    return result

print(won(john_williams_compositions))
英文:

Since you are a beginner and list comprehension might not look very sraightforward to you, here is a simple implementation:

def won(list):
result = []
for x in list:
if x['status'] == 'Won':
print(x['status'])
result.append(x)
return result
print(won(john_williams_compositions))

答案4

得分: 1

x 是一个 dict。与 JavaScript 不同,访问 dict 中给定键的值和访问属性值之间存在语法差异。

x["foo"] # 与键 "foo" 关联的值
x.foo # 与属性 "foo" 关联的值

你的循环需要使用前者:

def won(list):
    result = []
    for x in list:
        if x["status"] == "Won":
            result.append(x)
    return result
英文:

x is a dict. Unlike Javascript (I gather), there is a syntactic difference between access the value for a given key in a dict and accessing the value of an attribute.

x["foo"]  # Value associated with key "foo"
x.foo  # Value associated with the attribute "foo"

Your loop requires the former:

def won(list):
result = []
for x in list:
if x["status"] == "Won":
result.append[i]
return result

huangapple
  • 本文由 发表于 2023年5月20日 22:37:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76295754.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定