dict过滤 python_python-通过dict中的值过滤项目

您的卡片组是(词典的)列表,它没有.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'}]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值