例如,如何将列表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),具有这样的可变长度列表(但条目数在每行的两个列表中都匹配),并且每行都需要一个输出
答案 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}