并排打印 2 个列表

新手上路,请多包涵

我正在尝试使用列表理解并排输出 2 个列表的值。我在下面有一个示例,显示了我要完成的工作。这可能吗?

代码:

 #example lists, the real lists will either have less or more values
a = ['a', 'b', 'c,']
b = ['1', '0', '0']

str = ('``` \n'
       'results: \n\n'
       'options   votes \n'
       #this line is the part I need help with: list comprehension for the 2 lists to output the values as shown below
       '```')

print(str)

#what I want it to look like:
'''
results:

options  votes
a        1
b        0
c        0
'''

原文由 hwhat 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 798
2 个回答

您可以使用 zip() 函数将列表连接在一起。

 a = ['a', 'b', 'c']
b = ['1', '0', '0']
res = "\n".join("{} {}".format(x, y) for x, y in zip(a, b))

zip() 函数将使用每个列表中的相应元素迭代元组,然后您可以按照 Michael Butscher 在评论中建议的格式进行格式化。

最后,只需 join() 它们与换行符一起,您就拥有了想要的字符串。

 print(res)
a 1
b 0
c 0

原文由 SCB 发布,翻译遵循 CC BY-SA 3.0 许可协议

这有效:

 a = ['a', 'b', 'c']
b = ['1', '0', '0']

print("options  votes")

for i in range(len(a)):
    print(a[i] + '\t ' + b[i])

输出:

 options  votes
a        1
b        0
c        0

原文由 Ivan86 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题