我有一个字典和列表。我需要将字典(整数)的" 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"标签中找到。我怎么做?
我会这样做:
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内置。 - 没有必要的列表列表,订书者长1个元素。弄平它(
l = [1, 7, 9]
)
*另外,如果l
中的所有元素均为单元素列表,则可以使用以下内容,很可能会更快:
l = list(map(lambda x: [x], ids.intersection(x for y in l for x in y)))
正如其他人建议的,请使用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']
。
您也可以尝试此单线:
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]]
您可以这样做:
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!")
您可以尝试以下方法:
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!"
打印 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!")