字典列表的列表理解以分别为每个键获取值

List Comprehension for List of Dictionary to get Values Separately for Each Key

我想从给定的字典列表中获取城市名称及其各自的人口。我已经使用天真的方法并使用 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]

试试这个:

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]

由于 towns 是一个字典列表,使用列表推导式遍历它会 return 个字典元素。要访问存储在这些词典中的数据,您需要像在普通 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]

使用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]