验证列表元素是否存在于字典列表中并提取对应价格
问题解决:提取指定水果的价格列表
给定数据
有如下两个列表:
# 注意:原代码中元素未加引号,会触发变量未定义错误,这里先修正 fruits = ['apple', 'grapes', 'banana']
另一个名为attributes的列表:
[{'name': 'apple', 'color': 'red', 'price': '2'}, {'name': 'orange', 'color': 'orange', 'price': '6'}, {'name': 'grapes', 'color': 'green', 'price': '3'}, {'name': 'mango', 'color': 'yellow', 'price': '8'}, {'name': 'banana', 'color': 'yellow', 'price': '4'}]
需求
检查fruits列表的元素是否存在于attributes列表中,若存在则将对应的price值存入单独列表,期望输出[2, 3, 4]
错误代码问题分析
你尝试的代码存在3处问题:
- 语法错误:
if attribute['name'] is in fruits:里的is in是错误写法,正确判断成员关系用in即可 - 定义错误:
fruits = [apple,grapes,banana]中的元素未加引号,会被Python识别为未定义变量,触发NameError - 冗余操作:每次添加元素后执行
price = list(set(price)),这会打乱列表顺序,且attributes中每个水果唯一,无需去重
修正后的代码
基础循环版本
fruits = ['apple', 'grapes', 'banana'] attributes = [ {'name': 'apple', 'color': 'red', 'price': '2'}, {'name': 'orange', 'color': 'orange', 'price': '6'}, {'name': 'grapes', 'color': 'green', 'price': '3'}, {'name': 'mango', 'color': 'yellow', 'price': '8'}, {'name': 'banana', 'color': 'yellow', 'price': '4'} ] price = [] for attribute in attributes: if attribute['name'] in fruits: # 若需要整数类型可转int,否则直接存字符串 price.append(int(attribute['price'])) print(price) # 输出:[2, 3, 4]
简洁列表推导式版本
如果追求代码简洁,可使用列表推导式,同时将fruits转为集合提升查询效率:
fruits = {'apple', 'grapes', 'banana'} # 集合的成员查询效率高于列表 attributes = [ {'name': 'apple', 'color': 'red', 'price': '2'}, {'name': 'orange', 'color': 'orange', 'price': '6'}, {'name': 'grapes', 'color': 'green', 'price': '3'}, {'name': 'mango', 'color': 'yellow', 'price': '8'}, {'name': 'banana', 'color': 'yellow', 'price': '4'} ] price = [int(item['price']) for item in attributes if item['name'] in fruits] print(price) # 输出:[2, 3, 4]
内容的提问来源于stack exchange,提问作者Jimmy
相关产品推荐
相关产品推荐

