List Comprehension for List of Dictionary,为每个键分别获取值



我想从给定的字典列表中获得城市名称及其各自的人口在单独的列表中。我已经使用朴素方法和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]

try this:

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

相关内容

  • 没有找到相关文章

最新更新