如何使用 python while 循环打印地址为伯明翰的所有名字?

dictionary_list = [

    {"firstname": "Steven", "lastname": "Walker", "address": "Birmingham"},

    {"firstname": "James", "lastname": "Kay", "address": "Birmingham"},

    {"firstname": "Alice", "lastname": "Gibson", "address": "Birmingham"},

    {"firstname": "John", "lastname": "Doe", "address": "Birmingham"},

    {"firstname": "evan", "lastname": "spencer", "address": "Derby"},

    {"firstname": "Dean", "lastname": "Davis", "address": "Leeds"},

    {"firstname": "Jade", "lastname": "wilson", "address": "Birmingham"},

    {"firstname": "Emma", "lastname": "James", "address": "Birmingham"},

    {"firstname": "Alex", "lastname": "Windsor", "address": "Birmingham"},

    {"firstname": "Rebekah", "lastname": "Daphney", "address": "London"},

]

如何使用python while循环打印地址为伯明翰的所有名字?我不知道从哪里开始。


慕的地6264312
浏览 103回答 3
3回答

心有法竹

只是因为您要求使用while循环实现:i = 0while i < len(dictionary_list):&nbsp; &nbsp; d = dictionary_list[i]&nbsp; &nbsp; if d['address'] == 'Birmingham':&nbsp; &nbsp; &nbsp; &nbsp; print(d['firstname'])&nbsp; &nbsp; i += 1

慕妹3242003

您应该从 pandas 库开始,它是在 python 上开始操作数据最直观的:&nbsp; &nbsp; import pandas as pd&nbsp; &nbsp; df=pd.DataFrame(dictionary_list)&nbsp; &nbsp; df2 = df[df['address']=="Birmingham"]&nbsp; &nbsp; print(df2["firstname"])

阿波罗的战车

您首先不应该使用 awhile loop因为您的情况没有意义,您最好应该使用这样for loop的:for d in dictionary_list:&nbsp; &nbsp; if d['address'] == 'Birmingham':&nbsp; &nbsp; &nbsp; &nbsp; print([d['firstname'])但你可以按照alani 的建议,简单地在一行中完成此操作:print([d['firstname'] for d in dictionary_list if d['address'] == 'Birmingham'])
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python