Python 在字典中查找类似的列表值
我试图从我的列表中找到与字典值中的列表相匹配的值 例如,字典包含Python 在字典中查找类似的列表值,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,我试图从我的列表中找到与字典值中的列表相匹配的值 例如,字典包含 dict = {"test1": [1, 2, 3, 4], "test2": [2, 2, 3, 4], "test3": [1, 2, 4, 5], "test4": [6, 2, 3, 4], "test5": [7, 2, 3, 4]} 以及我需要的数据来找到匹配的if answer = [6,2,3,4] 我尝试拉任何测试,其中答案输入的第一个值
dict = {"test1": [1, 2, 3, 4],
"test2": [2, 2, 3, 4],
"test3": [1, 2, 4, 5],
"test4": [6, 2, 3, 4],
"test5": [7, 2, 3, 4]}
以及我需要的数据来找到匹配的if
answer = [6,2,3,4]
我尝试拉任何测试,其中答案输入的第一个值必须不同,其他值必须相同,例如
[(this is different), 2,3,4]
然后在最后,我希望记录
test1
、test2
和test5
。您可以迭代dict的项目,并将子列表的片段与要检查的列表片段进行比较:
d = {'test1':[1, 2, 3, 4], 'test2':[2, 2, 3, 4], 'test3':[1,2,4,5], 'test4':[6,2,3,4], 'test5':[7, 2, 3,4]}
def check(d, l):
for k, v in d.items():
if v != l and v[1:] == l[1:]:
yield k
print(list(check(d, [6, 2, 3, 4])))
这将产生:
['test1', 'test2', 'test5']
假设您有一个带有字符串键的有效字典,使用列表理解可以按如下方式过滤掉不需要的键:
>>> d = {
... "test1": [1, 2, 3, 4],
... "test2": [2, 2, 3, 4],
... "test3": [1, 2, 4, 5],
... "test4": [6, 2, 3, 4],
... "test5": [7, 2, 3, 4]
... }
>>> answer = [6, 2, 3, 4]
>>> [k for k, v in d.items() if v[0] != answer[0] and v[1:] == answer[1:]]
['test1', 'test2', 'test5']
请注意,
dict=…
覆盖内置函数dict
,这不是一个好主意。解决方案
dict_a = {
'test 1': [1, 2, 3, 4], 'test 2': [2, 2, 3, 4], 'test 3': [1, 2, 4, 5],
'test 4': [6, 2, 3, 4], 'test 5': [7, 2, 3, 4]
}
answer = [6, 2, 3, 4]
for i in dict_a:
if answer[0] != dict_a[i][0]:
if answer[1:4] == dict_a[i][1:4]:
print(dict_a[i])
存储输出
answer = [6, 2, 3, 4]
store = {}
for i in dict_a:
if answer[0] != dict_a[i][0]:
if answer[1:4] == dict_a[i][1:4]:
store[i] = dict_a[i]
for k in store:
print(f"{k}: {store[k]}")
输出
answer = [6, 2, 3, 4]
store = {}
for i in dict_a:
if answer[0] != dict_a[i][0]:
if answer[1:4] == dict_a[i][1:4]:
store[i] = dict_a[i]
for k in store:
print(f"{k}: {store[k]}")
我认为你的代码有几个问题。 首先,由于dict是一个关键字,所以应该避免将其作为变量名。 其次,没有定义变量test1、test2等。在这种情况下,最好使用“test1”、“test2”等 无论如何,请看下面的答案
dic = {'test1':[1, 2, 3, 4], 'test2':[2, 2, 3, 4], 'test3':[1,2,4,5],
'test4':[6,2,3,4], 'test5':[7, 2, 3,4]}
toMatch = [6,2,3,4]
matching = []
for (key, value) in dic.items():
if((value[1:]==toMatch[1:])&(value[0]!=toMatch[0])):
print(key,value)
matching.append(key)
print('Matching keys are:', matching)
答案是:
test1 [1, 2, 3, 4]
test2 [2, 2, 3, 4]
test5 [7, 2, 3, 4]
Matching keys are: ['test1', 'test2', 'test5']
<>请注意,这是一种你应该考虑抽象的函数。
def match_records(a, b):
return a[-3:] == b[-3:] and a[0] != b[0]
results = {k:v for k, v in d.items() if match_records(answers, v)}
你能分享你写的没有产生你想要的输出的代码吗?“所以最后我想要记录test1、test2和test5。”-你说的“被记录”是什么意思?我不清楚您想要实现什么。这甚至会返回测试4,但不应该是这样。你的情况不太好。您应该包括一个条件来检查第一个数字不应该是same@Onyambu哦,我错过了那个条件。