給定輸入串列:
L1 = [("A","p1",20), ("B","p2",30)]
L2 = [("A","p1",100), ("c","p3",35)]
預期輸出:
[(A,p1,20,100), (B,p2,30,"not in L2"), ("c","p3",35,"not in L1")]
我嘗試過使用兩個for回圈,一個是 for L1,另一個是 for,L2但它不適用于迭代元素并給出不需要的重復輸出。
uj5u.com熱心網友回復:
"A","p1"首先,創建一個包含所有可能的分組鍵( 、"B","p2"等)的字典。然后,遍歷此字典中的鍵以查找它是否存在于任一串列中。
L1 = [("A","p1",20), ("B","p2",30)]
L2 = [("A","p1",100), ("c","p3",35)]
d = {}
for x, y, z in L1 L2:
d[(x, y)] = [z] if not d.get((x, y)) else d[(x, y)] [z]
for k in d:
if k not in {(x, y) for x, y, z in L1}:
d[k] = ["not in L1"]
if k not in {(x, y) for x, y, z in L2}:
d[k] = ["not in L2"]
L = [(*k, *v) for k, v in d.items()]
print(L)
# [('A', 'p1', 20, 100), ('B', 'p2', 30, 'not in L2'), ('c', 'p3', 35, 'not in L1')]
如果您在一個串列中將鍵加倍,這將是安全的:
L1 = [("A","p1",20), ("B","p2",30)]
L2 = [("A","p1",100), ("A","p1",200), ("c","p3",35)]
那么結果將是
# [('A', 'p1', 20, 100, 200), ('B', 'p2', 30, 'not in L2'), ('c', 'p3', 35, 'not in L1')]
更多串列:
L1 = [("A","p1",20), ("B","p2",30)]
L2 = [("A","p1",100), ("c","p3",35)]
L3 = [("A","p1",200)]
d = {}
lists = ["L1", "L2", "L3"]
for x, y, z in [x for lst in lists for x in eval(lst)]:
d[(x, y)] = [z] if not d.get((x, y)) else d[(x, y)] [z]
for k in d:
for lst in lists:
if k not in {(x, y) for x, y, z in eval(lst)}:
d[k] = [f"not in {lst}"]
L = [(*k, *v) for k, v in d.items()]
print(L)
# [('A', 'p1', 20, 100, 200), ('B', 'p2', 30, 'not in L2', 'not in L3'), ('c', 'p3', 35, 'not in L1', 'not in L3')]
uj5u.com熱心網友回復:
L1 = [("A","p1",20), ("B","p2",30)]
L2 = [("A","p1",100), ("c","p3",35)]
# tranform L1, L2 to dict
D1 = dict((_[0], _) for _ in L1)
D2 = dict((_[0], _) for _ in L2)
out_dict = dict()
for k, v in D1.items():
if k in D2:
# use set to avoid duplicated value
new_tuple = D2[k] v
# keep the original order
sorted_list = sorted(set(new_tuple), key=new_tuple.index)
out_dict[k] = tuple(sorted_list)
else:
out_dict[k] = v ("not in L2",)
for k, v in D2.items():
if k in D1:
new_tuple = D1[k] v
sorted_list = sorted(set(new_tuple), key=new_tuple.index)
out_dict[k] = tuple(sorted_list)
else:
out_dict[k] = v ("not in L1",)
output = list(v for k, v in out_dict.items())
輸出:
[('A', 'p1', 20, 100),
('B', 'p2', 30, 'not in L2'),
('c', 'p3', 35, 'not in L1')]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/530216.html
下一篇:獲取兩個串列之間的重復項
