在 Python 中打印没有换行符(但有空格)的列表 [英] Printing a list without line breaks (but with spaces) in Python
问题描述
我正在尝试使用 sys.stdout.write()
打印没有换行符的列表的值.它工作得很好,但唯一的问题是我想将每个值与另一个值隔开.换句话说,我想要 1 2 3
而不是 123
.我在网站上寻找解决方案,但我还没有找到涉及列表的内容.
I'm trying to print the values of a list without line breaks using sys.stdout.write()
. It works great, but the only problem is that I want to space each value from another. In other words, instead of 123
, I want 1 2 3
. I looked on the website for a solution, but I haven't found something that involves lists.
当我将 " "
添加到 sys.stdout.write(list[i])
时,像这样:sys.stdout.write(list[i]], " ")
,它根本不打印.任何建议如何解决这个问题?
When I add " "
to sys.stdout.write(list[i])
, like this: sys.stdout.write(list[i], " ")
, it doesn't print at all. Any suggestions how to fix that?
这是我的代码:
import random
import sys
list = []
length = input("Please enter the number of elements to be sorted: ")
randomNums = input("Please enter the number of random integers to be created: ")
showList = raw_input("Would you like to see the unsorted and sorted list? y/n: ")
for i in range(length):
list.append(random.randint(1,randomNums))
if(showList == "y"):
for i in range(length):
sys.stdout.write(list[i], " ")
推荐答案
尝试
sys.stdout.write(" ".join(list))
以上仅当 list
包含字符串时才有效.使其适用于任何列表:
The above will only work if list
contains strings. To make it work for any list:
sys.stdout.write(" ".join(str(x) for x in list))
这里我们使用一个生成器表达式来转换列表中的每一项到一个字符串.
Here we use a generator expression to convert each item in the list to a string.
如果您的列表很大并且您想避免为其分配整个字符串,以下方法也适用:
If your list is large and you'd like to avoid allocating the whole string for it, the following approach will also work:
for item in list[:-1]:
sys.stdout.write(str(item))
sys.stdout.write(" ")
if len(list) > 0:
sys.stdout.write(list[-1])
正如在另一个答案中提到的,不要调用您的变量 list
.您实际上是在隐藏具有相同名称的内置类型.
And as mentioned in the other answer, don't call your variable list
. You're actually shadowing the built-in type with the same name.
这篇关于在 Python 中打印没有换行符(但有空格)的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!