如何在Python中将一个列表的值分配给第二个列表的值

时间:2019-05-14 19:06:33

标签: python-3.x

例如,如何将列表A的值连接到列表B的值

ListA = [1,2,3,4,5]
ListB = ["a","b","c","d","e"]

因此输出应返回类似

的内容
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

我有多行(26k),具有这样的可变长度列表(但条目数在每行的两个列表中都匹配),并且每行都需要一个输出

2 个答案:

答案 0 :(得分:1)

您可以将其放入字典,然后将每个项目添加到该字典中

ListA = [1, 2, 3, 4, 5]
ListB = ["a", "b", "c", "d", "e"]

ListC = []
# Generate a number for every item in ListA
for i in range(len(ListA)):
    # Take that number and use it as an index to append the value from ListA and ListB to ListC as a dictionary
    ListC.append({str(ListA[i]): ListB[i]})
# Print ListC
print(ListC)

"""
Output:
[{'1': 'a'}, {'2': 'b'}, {'3': 'c'}, {'4': 'd'}, {'5': 'e'}]
"""

要获取字典的输出,可以使用print(ListC[0]['1'])打印该字典,该字典将输出字母“ a”。零是索引标记(在python中始终从零开始),因此,如果您要打印特定数字的对应字母,则可以取数字,然后减去一个并将其放在第一组[]

说我想要'5'的字母。

# Number for the letter we want
num = "5"
# Calculate it's position in the dictionary
index = int(num) - 1
# Print that character
print(ListC[index][num])

"""
Output:
'e'
"""

您希望它的输出方式在Python上在语法上不正确,这是替代方法。

答案 1 :(得分:0)

在处理相同大小的多个列表时,zip是您的朋友

作为字符串列表,只需使用format并将其输入zip返回的元组

ListA = [1,2,3,4,5]
ListB = ["a","b","c","d","e"]

result_as_list = ["{}={}".format(*c) for c in zip(ListB,ListA)]

作为字典(可能更好,因为它不需要对字符串进行反向解析以获取键和值),只需将zip馈送到dict构造函数中即可:

result_as_dict = dict(zip(ListB,ListA))

输出:

>>> result_as_list
['a=1', 'b=2', 'c=3', 'd=4', 'e=5']
>>> result_as_dict
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}