搜索两个列表,并按正确的顺序为每对填写“无”

search two lists and fill with None for each pair in correct order

提问人:George 提问时间:11/1/2023 最后编辑:Goku - stands with PalestineGeorge 更新时间:11/1/2023 访问量:58

问:

这是的延续。

现在,结果是:

[{'type': 'POT'}, {'type': 'BOOK'}, {'type': 'GLASS'}]

如果找不到键,我想在结果中插入 a。None

所以,我想要:

[{'type': 'POT'}, {'type': 'BOOK'}, None, None, {'type': 'GLASS'}]

如果我尝试:

stuff_types = {

    "spana": {
        "type": "BOOK",
    },
    "geom": {
        "type": "GLASS",
    },
    "hlian": {
        "type": "POT",
        }
    }


a = ['kal', 'khp', 'khp', 'khp', 'geom']
b = ['hlian', 'spana', 'piper', 'meli', 'phin']


the_list = []
for tup in zip(a, b):
    for x in tup:
        if x in stuff_types:
            the_list.append(stuff_types[x])
        else:
             the_list.append(None)
            
print(the_list)

只是为了附加,我们收到对中每个元素的:NoneNone

('kal', 'hlian')
('khp', 'spana')
('khp', 'piper')
('khp', 'meli')
('geom', 'phin')

我想在正确的位置接收每对,而不是对中的每个元素。None

python-3.x 列表 字典

评论

0赞 quamrana 11/1/2023
请使用您现在看到的实际输出以及您真正希望看到的输出来更新您的问题。
0赞 George 11/1/2023
@quamrana:我一开始就已经有了这些信息。
0赞 MisterMiyagi 11/1/2023
所以你想要的是,如果对子的两部分都不匹配,那么应该选择吗?因此,搜索第一个默认值为 ?这看起来像一种标准的搜索算法,当找到一个项目并在末尾插入时(当没有搜索步骤触发 )。甚至只是一系列.NoneNonebreakNonebreakdict.get
0赞 JonSG 11/1/2023
这回答了你的问题吗?为什么是 dict.get(key) 而不是 dict[key]?

答:

1赞 Goku - stands with Palestine 11/1/2023 #1
stuff_types = {

    "spana": {
        "type": "BOOK",
    },
    "geom": {
        "type": "GLASS",
    },
    "hlian": {
        "type": "POT",
        }
    }


a = ['kal', 'khp', 'khp', 'khp', 'geom']
b = ['hlian', 'spana', 'piper', 'meli', 'phin']

有一个轻微的修改,你不需要嵌套的for循环:

the_list = []
for k,v in zip(a, b):
    if k in stuff_types:
        the_list.append(stuff_types[k])
    elif v in stuff_types:
        the_list.append(stuff_types[v])
    else:
        the_list.append(None)

print(the_list)

#output
[None, {'type': 'BOOK'}, None, None, {'type': 'GLASS'}]
2赞 quamrana 11/1/2023 #2

您需要测试每个项目,以查看其中任何一个是否具有相关键:tup

stuff_types = {

    "spana": {
        "type": "BOOK",
    },
    "geom": {
        "type": "GLASS",
    },
    "hlian": {
        "type": "POT",
        }
    }

def make_value(x,y):
    return stuff_types[x] if x in stuff_types else stuff_types[y] if y in stuff_types else None

a = ['kal', 'khp', 'khp', 'khp', 'geom']
b = ['hlian', 'spana', 'piper', 'meli', 'phin']


the_list = []
for (x,y) in zip(a, b):
    the_list.append(make_value(x,y))
            
print(the_list)

按要求输出:

[{'type': 'POT'}, {'type': 'BOOK'}, None, None, {'type': 'GLASS'}]

评论

0赞 JonSG 11/1/2023
简化一下怎么样?我知道这并不是严格意义上的一回事,但给定数据,结果应该是相同的。return stuff_types.get(x) or stuff_types.get(y)
1赞 RomanPerekhrest 11/1/2023 #3

使用单遍历,基于交叉点:set

res = [stuff_types[s.pop()] if (s := set(stuff_types) & set(p)) else None 
       for p in zip(a, b)]
print(res)

[{'type': 'POT'}, {'type': 'BOOK'}, None, None, {'type': 'GLASS'}]