在Python 3中打印空格分隔的元素列表

nic*_*kie 30 python pretty-print python-3.x

我有一个L元素列表,比如自然数.我想用一个空格作为分隔符将它们打印在一行中.但我不希望在列表的最后一个元素之后(或在第一个元素之前)有空格.

在Python 2中,可以使用以下代码轻松完成此操作.print声明的实现(神秘地,我必须承认)避免在换行符之前打印额外的空格.

L = [1, 2, 3, 4, 5]
for x in L:
    print x,
print
Run Code Online (Sandbox Code Playgroud)

但是,在Python 3中,似乎使用该print函数的(假设的)等效代码在最后一个数字之后产生一个空格:

L = [1, 2, 3, 4, 5]
for x in L:
    print(x, end=" ")
print()
Run Code Online (Sandbox Code Playgroud)

当然,我的问题很简单.我知道我可以使用字符串连接:

L = [1, 2, 3, 4, 5]
print(" ".join(str(x) for x in L))
Run Code Online (Sandbox Code Playgroud)

这是一个非常好的解决方案,但与Python 2代码相比,我发现它反直觉并且肯定更慢.另外,我知道我可以选择是否打印空间,例如:

L = [1, 2, 3, 4, 5]
for i, x in enumerate(L):
    print(" " if i>0 else "", x, sep="", end="")
print()
Run Code Online (Sandbox Code Playgroud)

但这再次比我在Python 2中所做的更糟糕.

所以,我的问题是,我在Python 3中遗漏了什么?我正在寻找的行为是否受到该print功能的支持?

Mar*_*ers 85

您可以将列表应用为单独的参数:

print(*L)
Run Code Online (Sandbox Code Playgroud)

并且让我们print()注意将每个元素转换为字符串.您可以像往常一样通过设置sep关键字参数来控制分隔符:

>>> L = [1, 2, 3, 4, 5]
>>> print(*L)
1 2 3 4 5
>>> print(*L, sep=', ')
1, 2, 3, 4, 5
>>> print(*L, sep=' -> ')
1 -> 2 -> 3 -> 4 -> 5
Run Code Online (Sandbox Code Playgroud)

除非您需要连接字符串用于其他内容,否则这是最简单的方法.否则,使用str.join():

joined_string = ' '.join([str(v) for v in L])
print(joined_string)
# do other things with joined_string
Run Code Online (Sandbox Code Playgroud)

请注意,这需要手动转换为字符串中的任何非字符串值L!

  • 该参考文献中 * 被称为什么?这个打印起诉 * 操作符叫什么?有人可以指出我的文档吗?谢谢 (3认同)
  • @nickie 在我的基准测试中:`lst = range(100*1000); 对于 lst 中的 i:打印 i,` 花费了 ~0.04s,而在 python3 中`lst = range(100*1000) ;打印(*lst)`花了~0.08s (2认同)
  • @NithinGowda:这是[调用表达式语法](https://docs.python.org/3/reference/expressions.html#calls)的一部分,我称之为*参数扩展*。这不是运营商。 (2认同)

小智 10

尽管接受的答案绝对明确,但我只是想检查时间方面的效率。

最好的方法是打印转换为字符串的连接数字字符串。

print(" ".join(list(map(str,l))))
Run Code Online (Sandbox Code Playgroud)

请注意,我使用了map而不是loop。我编写了所有 4 种不同方法来比较时间的一些代码:

import time as t

a, b = 10, 210000
l = list(range(a, b))
tic = t.time()
for i in l:
    print(i, end=" ")

print()
tac = t.time()
t1 = (tac - tic) * 1000
print(*l)
toe = t.time()
t2 = (toe - tac) * 1000
print(" ".join([str(i) for i in l]))
joe = t.time()
t3 = (joe - toe) * 1000
print(" ".join(list(map(str, l))))
toy = t.time()
t4 = (toy - joe) * 1000
print("Time",t1,t2,t3,t4)
Run Code Online (Sandbox Code Playgroud)

结果:

时间 74344.76 71790.83 196.99 153.99

输出结果让我非常惊讶。“循环方法”和“连接字符串方法”的时间差异巨大。

结论:如果列表大小太大(10**5 或更多),请勿使用循环打印列表。