如何在 python 中的两个数字列表之间建立关系

how to make a relation between two lists of number in python

具体问题是这样的:

我有two lists,即:

lst1 = [1,2,5,6,7];
lst2 = [11,12,13,14,15];

我想建立这些列表的关系以匹配其他列表的相应编号,例如1-11,5-13,7-15...如果我输入[1,5,7],它会自动生成[11,13,15].我是 python 的新手,所以我不知道它是否可行,或者有人可以给我一些建议或想法,在此先感谢!

您可以创建一个字典,其中第一个列表的元素作为键,第二个列表的元素作为值:

lst1 = [1,2,5,6,7]
lst2 = [11,12,13,14,15]

dct = dict((a, b) for a, b in zip(lst1, lst2))
# or even:
# dct = {a: b for a, b in zip(lst1, lst2)}
print(dct)  # {1: 11, 2: 12, 5: 13, 6: 14, 7: 15}
print(dct[1], dct[5], dct[7])  # 11 13 15

如果 "relation" 是指 1 对 1 映射,那么也许您应该看一下 dictionaries. And if your lists (lst1, lst2) always have same length and order of mapping, you probably don't need a dictionary mapping, just use indexing correctly, along with the index method for lists

首先 zip 两个列表然后使用 列表压缩 对列表的输出使用 if 条件

>>> lst1 = [1,2,5,6,7]

>>> lst2 = [11,12,13,14,15]

>>> input_lst = [1,2,5]

>>> [d for c,d in zip(lst1,lst2) if c in input_lst]      # first method Zip

>>> [lst2[lst1.index(v)] for v in (lst1) if v in input_lst]  # second mehod using index

输出

[11, 12, 13]

详情see

dict(zip(lst1, lst2))会好的

container = dict(zip(lst1, lst2))

print(container[1], container[5], container[7])