简体   繁体   English

并排打印2个列表

[英]Print 2 lists side by side

I'm trying to output the values of 2 lists side by side using list comprehension. 我正在尝试使用列表推导并排输出2个列表的值。 I have an example below that shows what I'm trying to accomplish. 下面有一个示例,显示了我要完成的工作。 Is this possible? 这可能吗?

code: 码:

#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
''' 

You can use the zip() function to join lists together. 您可以使用zip()函数将列表连接在一起。

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

The zip() function will iterate tuples with the corresponding elements from each of the lists, which you can then format as Michael Butscher suggested in the comments. zip()函数将使用每个列表中的相应元素迭代元组,然后可以按照注释中迈克尔·巴特歇尔(Michael Butscher)的建议进行格式化。

Finally, just join() them together with newlines and you have the string you want. 最后,只需join()它们与换行符一起join()即可获得所需的字符串。

print(res)
a 1
b 0
c 0

This works: 这有效:

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

print("options  votes")

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

Outputs: 输出:

options  votes
a        1
b        0
c        0
from __future__ import print_function  # if using Python 2

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

print("""results:

options\tvotes""")

for x, y in zip(a, b):
    print(x, y, sep='\t\t')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM