Python:横向打印而非当前默认打印
我在想,能不能在Python中像按行那样打印输出。
基本上,我有一个循环,可能会执行一百万次,我在这个循环中打印一些重要的计数。如果能像按行那样打印出来,那就太好了。
print x
# currently gives
# 3
# 4
#.. and so on
我想要的效果是这样的
print x
# 3 4
9 个回答
6
你不需要用for循环来做这个!
mylist = list('abcdefg')
print(*mylist, sep=' ')
# Output:
# a b c d e f g
这里我使用了一个叫做解包运算符的东西,符号是*
。在后台,打印函数其实是这样被调用的:print('a', 'b', 'c', 'd', 'e', 'f', 'g', sep=' ')
。
另外,如果你改变sep
参数的值,你可以自定义打印的方式,比如:
print(*mylist, sep='\n')
# Output:
# a
# b
# c
# d
# e
# f
# g
10
只需要在你要打印的项目后面加一个,
就可以了。
print(x,)
# 3 4
或者在Python 2中:
print x,
# 3 4
58
在Python2中:
data = [3, 4]
for x in data:
print x, # notice the comma at the end of the line
或者在Python3中:
for x in data:
print(x, end=' ')
输出结果是
3 4