在 Python 3 中打印以空格分隔的元素列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22556449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Print a list of space-separated elements in Python 3
提问by nickie
I have a list Lof elements, say natural numbers. I want to print them in one line with a single spaceas a separator. But I don't wanta space after the last element of the list (or before the first).
我有一个L元素列表,比如自然数。我想用一个空格作为分隔符将它们打印在一行中。但我不想在列表的最后一个元素之后(或第一个元素之前)有一个空格。
In Python 2, this can easily be done with the following code. The implementation of the printstatement (mysteriously, I must confess) avoids to print an extra space before the newline.
在 Python 2 中,这可以通过以下代码轻松完成。print语句的实现(神秘地,我必须承认)避免在换行符之前打印额外的空格。
L = [1, 2, 3, 4, 5]
for x in L:
print x,
print
However, in Python 3 it seems that the (supposedly) equivalent code using the printfunction produces a space after the last number:
但是,在 Python 3 中,使用该print函数的(据说)等效代码似乎在最后一个数字之后产生了一个空格:
L = [1, 2, 3, 4, 5]
for x in L:
print(x, end=" ")
print()
Of course there are easy answers to my question. I know I can use string concatenation:
当然,我的问题有很简单的答案。我知道我可以使用字符串连接:
L = [1, 2, 3, 4, 5]
print(" ".join(str(x) for x in L))
This is a quite good solution, but compared to the Python 2 code I find it counter-intuitive and definitely slower. Also, I know I can choose whether to print a space or not myself, like:
这是一个很好的解决方案,但与 Python 2 代码相比,我发现它违反直觉,而且速度肯定更慢。另外,我知道我可以自己选择是否打印空格,例如:
L = [1, 2, 3, 4, 5]
for i, x in enumerate(L):
print(" " if i>0 else "", x, sep="", end="")
print()
but again this is worse than what I had in Python 2.
但这又比我在 Python 2 中的情况更糟。
So, my question is, am I missing something in Python 3? Is the behavior I'm looking for supported by the printfunction?
所以,我的问题是,我是否在 Python 3 中遗漏了什么?该print功能是否支持我正在寻找的行为?
采纳答案by Martijn Pieters
You can apply the list as separate arguments:
您可以将列表作为单独的参数应用:
print(*L)
and let print()take care of converting each element to a string. You can, as always, control the separator by setting the sepkeyword argument:
让我们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
Unless you need the joined string for something else, this is the easiest method. Otherwise, use str.join():
除非您需要将连接字符串用于其他用途,否则这是最简单的方法。否则,请使用str.join():
joined_string = ' '.join([str(v) for v in L])
print(joined_string)
# do other things with joined_string
Note that this requires manual conversion to strings for any non-string values in L!
请注意,这需要手动将L! 中的任何非字符串值转换为字符串。
回答by mashkitty
list = [1, 2, 3, 4, 5]
for i in list[0:-1]:
print(i, end=', ')
print(list[-1])
do for loops really take that much longer to run?
for 循环真的需要更长的时间才能运行吗?
was trying to make something that printed all str values in a list separated by commas, inserting "and" before the last entry and came up with this:
试图制作一些将所有 str 值打印在以逗号分隔的列表中的东西,在最后一个条目之前插入“和”并想出了这个:
spam = ['apples', 'bananas', 'tofu', 'cats']
for i in spam[0:-1]:
print(i, end=', ')
print('and ' + spam[-1])
回答by Amit Dwivedi
Although the accepted answer is absolutely clear, I just wanted to check efficiency in terms of time.
尽管接受的答案绝对清楚,但我只是想检查时间方面的效率。
The best way is to print joined string of numbers converted to strings.
最好的方法是打印转换为字符串的数字连接字符串。
print(" ".join(list(map(str,l))))
Note that I used mapinstead of loop. I wrote a little code of all 4 different ways to compare time:
请注意,我使用了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)
Result:
结果:
Time 74344.76 71790.83 196.99 153.99
时间 74344.76 71790.83 196.99 153.99
The output was quite surprising to me. Huge difference of time in cases of 'loop method' and 'joined-string method'.
输出让我非常惊讶。“循环方法”和“连接字符串方法”的时间差异很大。
Conclusion: Do not use loops for printing list if size is too large( in order of 10**5 or more).
结论:如果尺寸太大(10**5 或更多),不要使用循环打印列表。
回答by TrickOrTreat
Joining elements in a list space separated:
将列表空间中的元素连接起来:
word = ["test", "crust", "must", "fest"]
word.reverse()
joined_string = ""
for w in word:
joined_string = w + joined_string + " "
print(joined_string.rstrim())

