我有一本字典和一份清单。我需要比较字典(整数)的“id”标签和列表元素。像这样:
l = [[1], [7], [9]]
dict = {
"first":{
"id": "0"
},
"second":{
"id": "7"
},
"third":{
"id": "4"
}
}
for i in l:
for j in dict:
if i == dict[j]["id"]:
print("Yay!")
else:
print("Nay!")
我希望能够检查列表'l'的任何元素是否可以在词典的“id”标记中找到。我怎么做?
答案 0 :(得分:3)
我会这样做:
l = [[1], [7], [9]]
dict_ = {
"first":{"id": "0"},
"second":{"id": "7"},
"third":{"id": "4"}
}
ids = set(int(v['id']) for _, v in dict_.items()) # set of all ids for quick membership testing
l = [sublist for sublist in l if sublist[0] in ids] # *
print(l) # -> [[7]]
我假设您要使用符合条件的项目修改(重新创建)l
列表。
注意:
dict
用作变量名称。你正在覆盖Python内置的。l = [1, 7, 9]
) *或者,如果l
中的所有元素都是单元素列表,您可以使用以下内容,这些内容很可能会明显加快:
l = list(map(lambda x: [x], ids.intersection(x for y in l for x in y)))
答案 1 :(得分:1)
正如其他人所建议的那样,请将ID作为列表而不是列表列表。那个filter
lst_ids = [1, 7, 9]
my_dict = {
"first":{
"id": "0"
},
"second":{
"id": "7"
},
"third":{
"id": "4"
}
}
filter(lambda k: int(my_dict[k]['id']) in lst_ids, my_dict)
这将返回匹配dict键的['second']
。
答案 2 :(得分:1)
你可以这样做:
l = [[1], [7], [9]]
dict = {
"first":{"id": "0"},
"second":{"id": "7"},
"third":{"id": "4"}
}
for i in l:
for j in dict:
if i[0] == int(dict[j]["id"]):
print("Yay!")
else:
print("Nay!")
答案 3 :(得分:1)
你也可以试试这个单行:
l = [[1], [7], [9]]
d = {"first":{ "id": "0"},
"second":{"id": "7"},
"third":{"id": "4"}}
l = [elem for elem in l if elem[0] in list(int(value['id']) for value in d.values())]
print(l)
输出:
[[7]]
或者您也可以使用filter
:
l = [[1], [7], [9]]
d = {"first":{ "id": "0"},
"second":{"id": "7"},
"third":{"id": "4"}}
resultValues = list(int(v['id']) for v in d.values())
l = list(filter(lambda i: i[0] in resultValues, l))
print(l)
输出:
[[7]]
答案 4 :(得分:0)
打印Yay!
和Nay!
时 - 转换为int并检入子列表?
l = [[1], [7], [9]]
dict1 = {
"first":{
"id": "0"
},
"second":{
"id": "7"
},
"third":{
"id": "4"
}
}
for i in l:
for j in dict1:
if int(dict1[j]['id']) in i:
print("Yay!")
else:
print("Nay!")
答案 5 :(得分:0)
你可以试试这个:
l = [[1], [7], [9]]
dict = {
"first":{
"id": "0"
},
"second":{
"id": "7"
},
"third":{
"id": "4"
}
}
final_dicts = [{a:b} for a, b in dict.items() if [int(b['id'])] in l]
print "Yay!" if final_dicts else "Nay"
输出:
"Yay!"