按字典中的值过滤项目

Dre*_*rew 5 python filtering python-3.x

我有一个像这样的字典设置:

deck = [{
         'name': 'drew',
         'lvl': 23,
         'items': ['sword', 'axe', 'mana_potion']},
        {
         'name': 'john',
         'lvl': 23,
         'items': ['sword', 'mace', 'health_potion']}]
Run Code Online (Sandbox Code Playgroud)

这是一个基本示例,我需要一种方法来过滤(仅复制 {characters})匹配某些值,例如我只想要 23 级或携带剑的角色。

我正在考虑做这样的事情:

filtered = filter_deck(deck, 'mace')

def filter_deck(self, deck, filt):
        return [{k:v for (k,v) in deck.items() if filt in k}]
Run Code Online (Sandbox Code Playgroud)

并返回:

filtered = [{
             'name': 'john',
             'lvl': 23,
             'items': ['sword', 'mace', 'health_potion']}]
Run Code Online (Sandbox Code Playgroud)

当我不知道它是单个值还是值列表或如何过滤多个值时,我不确定如何过滤 k:v 或 k:[v1,v2,v3] 等特定项目。

我不确定如何使用多个键过滤字符。假设我想筛选出 23 级的角色,或者有 items['sword'] 或 items['mace'] 的角色。我怎样才能让它排序filter_cards(deck, ['lvl'=23, 'items'=['sword','mace'])

因此,如果任何角色达到 23 级,或者携带狼牙棒或剑,他们就会出现在该列表中。

Ana*_*mar 3

你的deck是一个(字典)列表,它没有.items()。所以尝试做 -deck.items()会失败。

还有语法 -

filter_cards(deck, ['lvl'=23, 'items'=['sword','mace'])
Run Code Online (Sandbox Code Playgroud)

无效,您应该使用字典作为第二个元素。例子 -

filter_cards(deck, {'lvl':23, 'items':['sword','mace']})
Run Code Online (Sandbox Code Playgroud)

您应该使用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))
Run Code Online (Sandbox Code Playgroud)

演示 -

>>> 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'}]
Run Code Online (Sandbox Code Playgroud)