对初学者的一些帮助

我必须用 Python 3 的字典中的一些元素列出一个列表:


fruits = {

    'apple' : {'price' : '13', weight : '15'},

    'orange' : {'price' : '8', weight : '11'}

}

我怎样才能制作一个只显示所有水果价格的清单?


BIG阳
浏览 69回答 3
3回答

达令说

你可以使用operator.itemgetter如下from operator import itemgetterfruits = {'apple' : {'price' : '13', 'weight' : '15'}, 'orange' : {'price' : '8', 'weight' : '11'}}priceList = list(map(itemgetter('price'), fruits.values()))print(priceList)输出:['13', '8']

叮当猫咪

这会让你:fruits = {'apple' : {'price' : '13', 'weight' : '15'}, 'orange' : {'price' : '8',          'weight' : '11'}}output = {k:v['price'] for k,v in fruits.items()}print(output)结果是:{'apple': '13', 'orange': '8'}

largeQ

您可以使用列表理解来获取水果价格列表:fruits = {    "apple": {"price": "13", "weight": "15"},    "orange": {"price": "8", "weight": "11"},}# using list comprehensionfruits_prices = [fruit_info.get("price") for fruit_info in fruits.values()]# using loopfruit_prices = []for fruit_info in fruits.values():    fruit_prices.append(fruit_info.get("price"))print(fruit_prices)这为您提供了水果价格列表:['13', '8']
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python