您的卡片组是(词典的)列表,它没有.items().因此尝试执行-deck.items()将失败.
还有语法-
filter_cards(deck, ['lvl'=23, 'items'=['sword','mace'])
无效,您应该使用字典作为第二个元素.范例-
filter_cards(deck, {'lvl':23, 'items':['sword','mace']})
如果字典包含值之一,则应使用filter()内置函数以及返回True的函数.范例-
def filter_func(dic, filterdic):
for k,v in filterdic.items():
if k == 'items':
if any(elemv in dic[k] for elemv in v):
return True
elif v == dic[k]:
return True
return False
def filter_cards(deck, filterdic):
return list(filter(lambda dic, filterdic=filterdic: filter_func(dic, filterdic) , deck))
演示-
>>> deck = [{
... 'name': 'drew',
... 'lvl': 23,
... 'items': ['sword', 'axe', 'mana_potion']},{
... 'name': 'john',
... 'lvl': 23,
... 'items': ['sword', 'mace', 'health_potion']},{
... 'name': 'somethingelse',
... 'lvl': 10,
... 'items': ['health_potion']}]
>>>
>>>
>>> filter_cards(deck, {'lvl':23, 'items':['sword','mace']})
[{'lvl': 23, 'items': ['sword', 'axe', 'mana_potion'], 'name': 'drew'}, {'lvl': 23, 'items': ['sword', 'mace', 'health_potion'], 'name': 'john'}]