使用字典和子列表从列表中搜索并创建新列表

2024-09-30 01:18:42 发布

您现在位置:Python中文网/ 问答频道 /正文

这里我有一个带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')  

Tags: 列表searchsize字典valueattributebluecolor
3条回答

您必须查看该值是否在列表中,而不是是否等于它。此外,使用全局brands变量会给您带来问题,请将其保留在函数中并返回品牌列表

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'],
    },
]


def search(attribute, value):
    brands = []
    for d in tshirts:
        if value in d[attribute]:
            brands.append(d['brand'])
    return brands


print(search('color', 'blue'))  # ['A', 'B', 'C']

您也可以通过列表理解来完成此操作:

def search(attribute, value):
    return [d['brand'] for d in tshirts if value in d[attribute]]
brands = []
def search(attribute, value):
    for d in tshirts:
        if value in d[attribute] :
            brands.append(d['brand'])
    print(brands)

search('color', 'blue')

以下方面应起作用:

brands=[i['brand'] for i in tshirts if 'blue' in i['color']]

相关问题 更多 >

    热门问题