我想连接列表中的项目以使用其中每个项目创建另一个列表:
例如:
answers = ["RAM", "PC", "WAN"]
terms = ["Random Access Memory", "Personal Computer", "Wide Area Network"]
我想要发生的事情:
combination = [RAM - Random Access Memory]
zip()
会在这里提供帮助,它将把任意数量的可迭代对象收集成块,并以其中最短的一个结束
>>> for values in zip([1,2], [3,4], [5,6,7]):
... print(values)
...
(1, 3, 5)
(2, 4, 6) # NOTE 7 is lost
达到此结果的途径有很多,但较长的版本可能有助于更清楚地了解正在发生的事情
result = []
for answer, term in zip(answers, terms): # unpacks terms
together = f"{answer} - {term}"
result.append(together)