这里我有一个带T恤的字典列表。我想在字典里搜索“蓝色”衬衫,并创建一个有这种颜色的品牌的列表。我的代码返回一个空列表
tshirts=[
{'brand': 'A',
'color': ['blue', 'white', 'black'],
'size': ['XS', 'M', 'L']},
{'brand': 'B',
'color': ['blue', 'red', 'black'],
'size': ['S', 'M', 'L']},
{'brand': 'C',
'color': ['blue', 'white', 'yellow'],
'size': ['S', 'M', 'XL']}
]
brands=[]
def search(attribute, value):
for d in tshirts:
if d[attribute] == value:
brands.append(d['brand'])
print(brands)
search('color', 'blue')
您必须查看该值是否在列表中,而不是是否等于它。此外,使用全局
brands
变量会给您带来问题,请将其保留在函数中并返回品牌列表您也可以通过列表理解来完成此操作:
以下方面应起作用:
相关问题 更多 >
编程相关推荐