我想從給定的字典串列中獲取城市名稱及其各自的人口。我已經使用幼稚的方法和使用map()函式實作了這一點,但我需要使用串列理解技術來執行它。我試過下面的代碼,但它沒有給出正確的輸出。我應該做哪些修改,請評論。謝謝。
towns = [{'name': 'Manchester', 'population': 58241},
{'name': 'Coventry', 'population': 12435},
{'name': 'South Windsor', 'population': 25709}]
print('Name of towns in the city are:', [item for item in towns[item]['name'].values()])
print('Population of each town in the city are:', [item for item in towns[item]['population'].values()])
** 預期產出 **
城市中的城鎮名稱為:['Manchester', 'Coventry', 'South Windsor']
全市各鎮人口分別為:[58241、12435、25709]
uj5u.com熱心網友回復:
嘗試這個 :
towns = [{'name': 'Manchester', 'population': 58241},
{'name': 'Coventry', 'population': 12435},
{'name': 'South Windsor', 'population': 25709}]
print('Name of towns in the city are:',
[town['name'] for town in towns])
print('Population of each town in the city are:',
[town['population'] for town in towns])
輸出:
Name of towns in the city are: ['Manchester', 'Coventry', 'South Windsor']
Population of each town in the city are: [58241, 12435, 25709]
uj5u.com熱心網友回復:
因為towns是一個字典串列,所以使用串列推導遍歷它會回傳字典元素。要訪問存盤在這些字典中的資料,您需要像在正常for回圈中一樣索引串列理解的元素:
towns = [{'name': 'Manchester', 'population': 58241},
{'name': 'Coventry', 'population': 12435},
{'name': 'South Windsor', 'population': 25709}]
names = [item["name"] for item in towns]
populations = [item["population"] for item in towns]
print("Name of towns in the city are:", names)
print("Population of each town in the city are:", populations)
這類似于以下for回圈:
towns = [{'name': 'Manchester', 'population': 58241},
{'name': 'Coventry', 'population': 12435},
{'name': 'South Windsor', 'population': 25709}]
names = []
populations = []
for town in towns:
names.append(town["name"])
populations.append(town["population"])
print("Name of towns in the city are:", names)
print("Population of each town in the city are:", populations)
兩者都產生相同的輸出:
Name of towns in the city are: ['Manchester', 'Coventry', 'South Windsor']
Population of each town in the city are: [58241, 12435, 25709]
uj5u.com熱心網友回復:
使用map()方法
towns = [{'name': 'Manchester', 'population': 58241},
{'name': 'Coventry', 'population': 12435},
{'name': 'South Windsor', 'population': 25709}]
print('Name of towns in the city are:', list(map(lambda k:k['name'], towns)))
print('Population of each town in the city are:', list(map(lambda v:v['population'], towns)))
輸出
城市中的城鎮名稱為:['Manchester', 'Coventry', 'South Windsor']
全市各鎮人口分別為:[58241、12435、25709]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/488140.html
標籤:Python python-3.x 列表 字典 列表理解
下一篇:將父子字典串列轉換為嵌套字典
