我有一个排序的整数ID列表,例如
[1, 2, 10, 15, 16, 17, 20, 34, ...]
在按ID排序的ID旁边,我有一个代码元组(tuple1),
((1, "A"), (2, "A"), (15, "B"), (16, "A"), (17, "B"), (34, "B"), ...)
我还有另一个元组(tuple2),其格式相同,例如
((1, "B"), (2, "B"), (10, "B"), (16, "A"), (17, "B"), (34, "B"), ...)
我想将元组组合成一个字典,其中键是ID,值是一个列表,该列表按顺序包含来自tuple1的代码和来自tuple2的代码。如果该ID存在于ID列表中,但不存在于元组中,则该值应为"N/A"
。
因此,使用以上数据,应产生以下内容:
{1: ["A", "B"], 2: ["A", "B"], 10: ["N/A", "B"], 15: ["B", "N/A"],
16: ["A", "A"], 17: ["B", "B"], 20: ["N/A", "N/A"], 34: ["B", "B"]}
我花了很长时间思考这个问题,但我无法提出解决方案。如果有人可以帮助我弄清楚如何在Python中运行它,那将非常有帮助。
谢谢。
编辑:这不是重复的,这个问题要复杂得多。
答案 0 :(得分:10)
如果将元组的元组放入字典中,将容易得多。如果缺少密钥,请使用get
为字典设置默认值:
ids = [1, 2, 10, 15, 16, 17, 20, 34]
tup1 = ((1, "A"), (2, "A"), (15, "B"), (16, "A"), (17, "B"), (34, "B"))
tup2 = ((1, "B"), (2, "B"), (10, "B"), (16, "A"), (17, "B"), (34, "B"))
tup1 = dict(tup1)
tup2 = dict(tup2)
{k: [tup1.get(k, 'N/A'), tup2.get(k, 'N/A')] for k in ids}
答案 1 :(得分:3)
这是对此的一种可能的解决方案:
from collections import defaultdict
keys = [1, 2, 10, 15, 16, 17, 20, 34]
t1 = ((1, "A"), (2, "A"), (15, "B"), (16, "A"), (17, "B"), (34, "B"))
t2 = ((1, "B"), (2, "B"), (10, "B"), (16, "A"), (17, "B"), (34, "B"))
merge_d = defaultdict(list)
for d in map(dict, (t1, t2)):
for k in keys:
merge_d[k].append(d.get(k, "N/A"))
结果字典将包含:
>>> merge_d
defaultdict(<class 'list'>, {1: ['A', 'B'], 2: ['A', 'B'], 10: ['N/A', 'B'], 15: ['B', 'N/A'], 16: ['A', 'A'], 17: ['B', 'B'], 20: ['N/A', 'N/A'], 34: ['B', 'B']})
答案 2 :(得分:0)
有点粗大,但是您无需转换为字典就可以做到:
myList = [1, 2, 10, 15, 16, 17, 20, 34]
tuples1 = ((1, "A"), (2, "A"), (15, "B"), (16, "A"), (17, "B"), (34, "B"))
tuples2 = ((1, "B"), (2, "B"), (10, "B"), (16, "A"), (17, "B"), (34, "B"))
myDict = {}
for i in myList:
myDict[i] = ["N/A","N/A"]
for t in tuples1:
if(t[0]) in myList:
for key in myDict:
if key == t[0]:
myDict[key][0] = t[1]
for t in tuples2:
if(t[0]) in myList:
for key in myDict:
if key == t[0]:
myDict[key][1] = t[1]
print(myDict)
赠予:
{1:['A','B'],2:['A','B'],10:['N / A','B'],15:['B',' N / A'],16:['A','A'],17:['B','B'],20:['N / A','N / A'],34:[' B','B']}
答案 3 :(得分:0)
这可以通过另一种方式完成!
lis=[1, 2, 10, 15, 16, 17, 20, 34]
tuple1=((1, "A"), (2, "A"), (15, "B"), (16, "A"), (17, "B"), (34, "B"))
tuple2=((1, "B"), (2, "B"), (10, "B"), (16, "A"), (17, "B"), (34, "B"))
z={**dict.fromkeys(lis,'N/A'), **dict(tuple1)}
y={**dict.fromkeys(lis, 'N/A'), **dict(tuple2)}
ds = [z, y]
d = {}
for k in y.keys():
d[k] = list(d[k] for d in ds)
答案 4 :(得分:0)
我的两分钱:一种单行解决方案,基于@busybear的回答,能够处理任意数量的元组:
ids = [1, 2, 10, 15, 16, 17, 20, 34]
vals = (
((1, "A"), (2, "A"), (15, "B"), (16, "A"), (17, "B"), (34, "B"),),
((1, "B"), (2, "B"), (10, "B"), (16, "A"), (17, "B"), (34, "B"),),
)
d = {i: [d.get(i, 'N/A') for d in map(dict, vals)] for i in ids}