如果我有以下情况:
team = [
{'name': 'Ben', 'age': 31, 'country': 'France', 'hobbies': ['coding', 'biking']},
{'name': 'Quinn', 'age': 26, 'country': 'Ireland', 'hobbies': ['skiing']},
{'name': 'Sasha', 'age': 24, 'country': 'Lebanon', 'hobbies': ['sports']},
{'name': 'Alex', 'age': 28, 'country': 'Austria', 'hobbies': []}
]对于一个人来说,我怎样才能算出“业余爱好”中的项目,比如说本。我尝试了let()、sum()和一些If语句,但都没有效果。也许我只是在语法上弄错了,或者错过了一步。能帮我找到正确的方向吗?
我怎样才能打印列出的兴趣爱好的数量,例如,本2,萨沙1等等。
发布于 2022-07-21 15:35:15
使用len,如下所示:
team = [
{'name': 'Ben', 'age': 31, 'country': 'France', 'hobbies': ['coding', 'biking']},
{'name': 'Quinn', 'age': 26, 'country': 'Ireland', 'hobbies': ['skiing']},
{'name': 'Sasha', 'age': 24, 'country': 'Lebanon', 'hobbies': ['sports']},
{'name': 'Alex', 'age': 28, 'country': 'Austria', 'hobbies': []}
]
for player in team:
print('%s has %d hobbies' % (player['name'], len(player['hobbies'])))输出:
Ben has 2 hobbies
Quinn has 1 hobbies
Sasha has 1 hobbies
Alex has 0 hobbies发布于 2022-07-21 15:38:04
嗯,你可以试试这样的东西:
counts = {person["name"]:len(person.get("hobbies",[])) for person in team}发布于 2022-07-21 16:09:07
或者您可以使用.__len__()作为解决方案:
team = [
{'name': 'Ben', 'age': 31, 'country': 'France', 'hobbies': ['coding', 'biking']},
{'name': 'Quinn', 'age': 26, 'country': 'Ireland', 'hobbies': ['skiing']},
{'name': 'Sasha', 'age': 24, 'country': 'Lebanon', 'hobbies': ['sports']},
{'name': 'Alex', 'age': 28, 'country': 'Austria', 'hobbies': []}
]
for person in team:
if person["hobbies"].__len__() > 1:
print(person["name"],"has",str(person["hobbies"].__len__()),"hobbies")
else:
print(person["name"],"has",str(person["hobbies"].__len__()),"hobby")产出:
Ben has 2 hobbies
Quinn has 1 hobby
Sasha has 1 hobby
Alex has 0 hobbyhttps://stackoverflow.com/questions/73068976
复制相似问题