提问人:George 提问时间:11/1/2023 最后编辑:Goku - stands with PalestineGeorge 更新时间:11/1/2023 访问量:58
搜索两个列表,并按正确的顺序为每对填写“无”
search two lists and fill with None for each pair in correct order
问:
这是此的延续。
现在,结果是:
[{'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)
只是为了附加,我们收到对中每个元素的:None
None
('kal', 'hlian')
('khp', 'spana')
('khp', 'piper')
('khp', 'meli')
('geom', 'phin')
我想在正确的位置接收每对,而不是对中的每个元素。None
答:
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'}]
评论
None
None
break
None
break
dict.get