例如,我有一个列表a
。当我在for循环中执行它时,我可以打印它的所有元素。但是当我在for循环之外执行它时,它只打印最后一个。如何在for循环外打印它们?提前谢谢。
代码:
a=['a is apple','b is banana','c is cherry']
for i in a:
print(i)
print("====================")
print(i)
打印:
a is apple
b is banana
c is cherry
====================
c is cherry
我想要的结果是:
a is apple
b is banana
c is cherry
====================
a is apple
b is banana
c is cherry
答案 0 :(得分:4)
您可以将print
与*
和换行符的分隔符一起使用:
print(*a, sep='\n')
print("====================")
print(*a, sep='\n')
输出:
a is apple
b is banana
c is cherry
====================
a is apple
b is banana
c is cherry
print(*a)
相当于print(a[0], a[1], a[2], ...)
。
这将打印它之间的空白区域。
使用sep='\n'
覆盖此默认设置会为您提供换行符。
如果要重复使用它,请编写自己的小辅助函数:
def myprint(a):
print(*a, sep='\n')
myprint(a)
单行代理,但可读性较差:
print(*(a + ["=" * 20] + a), sep='\n')
输出:
a is apple
b is banana
c is cherry
====================
a is apple
b is banana
c is cherry
在Python 2中,使用以下命令“打开”Python-3样式的打印功能:
from __future__ import print_function
答案 1 :(得分:1)
您可以使用join()
并将列表传递给它,如下所示:
a=['a is apple','b is banana','c is cherry']
print("\n".join(a))
print("====================")
print("\n".join(a))
输出
a is apple
b is banana
c is cherry
====================
a is apple
b is banana
c is cherry
答案 2 :(得分:1)
您可以将列表乘以2并在列表中间添加分隔符,然后使用join
方法打印列表。
l = ['a is apple','b is banana','c is cherry']
l = l*2
#['a is apple', 'b is banana', 'c is cherry', 'a is apple', 'b is banana', 'c is cherry']
l = l.insert(int(len(l)/2), '====================')
#['a is apple', 'b is banana', 'c is cherry', '====================','a is apple', 'b is banana', 'c is cherry']
print('\n'.join(l))
这将输出:
a is apple
b is banana
c is cherry
====================
a is apple
b is banana
c is cherry
答案 3 :(得分:0)
试试这个。这将提供您需要的东西
x,y,z=a
print(x,y,z)
答案 4 :(得分:0)
这是最简单,最干净的方法(在Python 2和3中通用):
print('\n'.join(a + ["===================="] + a))
这是仅限Python-3的版本:
print(*(a + ["===================="] + a), sep='\n')