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循环打印地址为伯明翰的所有名字?我不知道从哪里开始。
3 回答
心有法竹
TA贡献1866条经验 获得超5个赞
只是因为您要求使用while循环实现:
i = 0
while i < len(dictionary_list):
d = dictionary_list[i]
if d['address'] == 'Birmingham':
print(d['firstname'])
i += 1
慕妹3242003
TA贡献1824条经验 获得超6个赞
您应该从 pandas 库开始,它是在 python 上开始操作数据最直观的:
import pandas as pd
df=pd.DataFrame(dictionary_list)
df2 = df[df['address']=="Birmingham"]
print(df2["firstname"])
阿波罗的战车
TA贡献1862条经验 获得超6个赞
您首先不应该使用 awhile loop因为您的情况没有意义,您最好应该使用这样for loop的:
for d in dictionary_list:
if d['address'] == 'Birmingham':
print([d['firstname'])
但你可以按照alani 的建议,简单地在一行中完成此操作:
print([d['firstname'] for d in dictionary_list if d['address'] == 'Birmingham'])
添加回答
举报
0/150
提交
取消