python比较dicts列表和元组列表

问题描述 投票:-4回答:3

我有一个dicts列表和元组列表。 dicts列表是一种查找表。基于对,我必须获得键和非匹配我需要获得'NA'键。

e.g

lookup_table = [
        {"L" : (148, -1) },
        {"D" : (148,440) },
        {"N1" : (148,441)},
        {"C" : (148,443) }]

data= [(10,10),(15,15),(148,-1) ,(148,440),(148,443)]

我的结果应该是

res = ['NA': (10,10), 'NA': (15,15),"L" : (148, -1),"D" : (148,440),"C" : (148,443) ]

我知道如何获得比赛,但我正在努力争取'NA'

因为我有多个具有相同名称的密钥,所以这种方法甚至可以用python实现吗?

谢谢

python list dictionary compare
3个回答
0
投票

NA是您词典的关键,它必须是唯一的值。所以,你最好使用list作为结果。像res = [['N/A', (10,10)],['L', (148, -1)]]之类的东西


0
投票

你的res显示了一个列表。但是,似乎你想要一个dictionary代替。

res = ['NA': (10,10), 'NA': (15,15),"L" : (148, -1),"D" : (148,440),"C" : (148,443) ]

所以你可能会尝试这样做:

res = { 'NA': (10,10), 'NA': (15,15),"L" : (148, -1),"D" : (148,440),"C" : (148,443) }

然而,这仍然是无效的,因为'NA'是一个key,它应该是独一无二的。那么你应该做的是拥有一个list of dictionaries,一个list of tuples或一个list of lists

# List of Dictionaries:
res = [{'NA': (10,10)}, {'NA': (15,15}), {'L' : (148, -1)}, {'D' : (148,440)},{'C' : (148,443)} ]

# List of Tuples
res = [('NA', (10,10)), ('NA', (15,15)),('L', (148, -1)), ('D', (148,440)), ('C', (148,443)) ]

# List of Lists
res = [['NA', (10,10)], ['NA', (15,15)], ['L', (148, -1)], ['D', (148,440)], ['C', (148,443)]]

我不确定哪一个最适合你想要实现的目标。


0
投票

所以使用你的一些建议解决了它

首先,我将查找表转换为列表列表。其次是代码

new_data_woshi = []
#add 'NA' to all in my data list of tuples
for rec in data_woshi:
    new_data_woshi.append(['NA', rec])

#go trough loopkup if there is a match replace the current element
for rec in new_data_woshi:
    for a in lookup_table:
        if rec[1] == a[1]:
            rec[0] = a[0]
© www.soinside.com 2019 - 2024. All rights reserved.