我在想是否可以在两个列表之间执行“配对”(因此一个列表就像对另一个列表的答案一样)。
假设 LIST A (从迭代中获得)是这样的:
[RESULT 1, X]
[RESULT 2, Y]
[RESULT 3, X, Y]
[RESULT 4, Z, Y]
[RESULT 5, Z]
[RESULT 6, Z, X]
LIST 2 是:
[X, 12, 56, 2]
[Y, 100]
[Z, 22, 78, 00, 01, 5]
我想用 LIST1 替换X,Y,Z ......各自的数据(可在 LIST2 中找到,所以最终的结果是像这样:
[RESULT 1, [X, 12, 56, 2]]
[RESULT 3, [X, 12, 56, 2], [Y, 100]]
or
[RESULT 1, X, 12, 56, 2]
[RESULT 3, X, 12, 56, 2, Y, 100]
达到此目的的pythonic方式是什么?
非常感谢您的帮助。
答案 0 :(得分:1)
list1 = [['RESULT 1', 'X'],
['RESULT 2', 'Y'],
['RESULT 3', 'X', 'Y'],
['RESULT 4', 'Z', 'Y'],
['RESULT 5', 'Z'],
['RESULT 6', 'Z', 'X']]
list2 = [['X', 12, 56, 2],
['Y', 100],
['Z', 22, 78, 00, 1, 5]]
map2 = {item[0]: item[1:] for item in list2}
for item in list1:
for pos, sub_item in enumerate(item):
item[pos] = map2.get(sub_item, sub_item)
答案 1 :(得分:0)
使用For循环
list1=[['RESULT 1', 'X'],
['RESULT 2', 'Y'],
['RESULT 3', 'X', 'Y'],
['RESULT 4','Z', 'Y'],
['RESULT 5','Z'],
['RESULT 6', 'Z', 'X']]
list2=[['X', '12', '56', '2'],
['Y', '100'],
['Z', '22', '78', '00', '01', '5']]
for i in list1:
for j in range(len(i)):
for k in list2:
if(i[j]==k[0]):
i[j]=k
print(list1)
Ouptput:
[['RESULT 1', ['X', '12', '56', '2']],
['RESULT 2', ['Y', '100']],
['RESULT 3', ['X', '12', '56', '2'], ['Y', '100']],
['RESULT 4', ['Z', '22', '78', '00', '01', '5'], ['Y', '100']],
['RESULT 5', ['Z', '22', '78', '00', '01', '5']],
['RESULT 6', ['Z', '22', '78', '00', '01', '5'], ['X', '12', '56', '2']]]
答案 2 :(得分:0)
您可以使用嵌套字典,避免显式for
循环。
lst1 = [['RESULT 1', 'X'],
['RESULT 2', 'Y'],
['RESULT 3', 'X', 'Y'],
['RESULT 4', 'Z', 'Y'],
['RESULT 5', 'Z'],
['RESULT 6', 'Z', 'X']]
lst2 = [['X', 12, 56, 2],
['Y', 100],
['Z', 22, 78, 0, 1, 5]]
dict_values = {k[0]: k[1:] for k in lst2}
res = {k[0]: dict(zip(k[1:], map(dict_values.get, k[1:]))) for k in lst1}
<强>结果强>
{'RESULT 1': {'X': [12, 56, 2]},
'RESULT 2': {'Y': [100]},
'RESULT 3': {'X': [12, 56, 2], 'Y': [100]},
'RESULT 4': {'Y': [100], 'Z': [22, 78, 0, 1, 5]},
'RESULT 5': {'Z': [22, 78, 0, 1, 5]},
'RESULT 6': {'X': [12, 56, 2], 'Z': [22, 78, 0, 1, 5]}}
更接近您想要的输出,您可以使用列表推导:
res2 = {k[0]: [[k[i]] + dict_values[k[i]] for i in range(1, len(k))] for k in lst1}
# {'RESULT 1': [['X', 12, 56, 2]],
# 'RESULT 2': [['Y', 100]],
# 'RESULT 3': [['X', 12, 56, 2], ['Y', 100]],
# 'RESULT 4': [['Z', 22, 78, 0, 1, 5], ['Y', 100]],
# 'RESULT 5': [['Z', 22, 78, 0, 1, 5]],
# 'RESULT 6': [['Z', 22, 78, 0, 1, 5], ['X', 12, 56, 2]]}