我正在尝试使用list comprehension并排输出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
'''
您可以使用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()
与newlines一起使用即可获得所需的字符串。
print(res)
a 1
b 0
c 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
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')