Python - 打印出用逗号分隔的列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32796452/
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
Python - printing out list separated with comma
提问by user2092743
I am writing a piece of code that should output a list of items separated with a comma. The list is generated with a for loop. I use the
我正在编写一段代码,它应该输出一个用逗号分隔的项目列表。该列表是使用 for 循环生成的。我用
for x in range(5):
print(x, end=",")
The problem is I don't know how to get rid of the last comma that is added with the last entry in the list. It outputs this:
问题是我不知道如何去掉与列表中最后一个条目一起添加的最后一个逗号。它输出这个:
0,1,2,3,4,
How do I remove the ending ' , ' ?
如何删除结尾 ' , ' ?
采纳答案by Graeme Stuart
Pass sep=","
as an argument to print()
sep=","
作为参数传递给print()
You are nearly there with the print statement.
您几乎可以使用 print 语句。
There is no need for a loop, printhas a sep
parameter as well as end
.
不需要循环,print有一个sep
参数以及end
.
>>> print(*range(5), sep=", ")
0, 1, 2, 3, 4
A little explanation
一点解释
The print
builtin takes any number of items as arguments to be printed. Any non-keyword arguments will be printed, separated by sep
. The default value for sep
is a single space.
所述print
内置需要作为要打印参数中的任何数量的项目。任何非关键字参数都将被打印出来,以sep
. 的默认值为sep
单个空格。
>>> print("hello", "world")
hello world
Changing sep
has the expected result.
改变sep
有预期的结果。
>>> print("hello", "world", sep=" cruel ")
hello cruel world
Each argument is stringified as with str()
. Passing an iterable to the print statement will stringify the iterable as one argument.
每个参数都被字符串化为str()
。将可迭代对象传递给打印语句会将可迭代对象字符串化为一个参数。
>>> print(["hello", "world"], sep=" cruel ")
['hello', 'world']
However, if you put the asterisk in front of your iterable this decomposes it into separate arguments and allows for the intended use of sep
.
但是,如果您将星号放在可迭代对象前面,则会将其分解为单独的参数并允许预期使用sep
.
>>> print(*["hello", "world"], sep=" cruel ")
hello cruel world
>>> print(*range(5), sep="---")
0---1---2---3---4
Using join
as an alternative
使用join
作为替代
The alternative approach for joining an iterable into a string with a given separator is to use the join
method of a separator string.
使用给定分隔符将可迭代对象连接到字符串的另一种方法是使用join
分隔符字符串的方法。
>>>print(" cruel ".join(["hello", "world"]))
hello cruel world
This is slightly clumsier because it requires non-string elements to be explicitly converted to strings.
这有点笨拙,因为它需要将非字符串元素显式转换为字符串。
>>>print(",".join([str(i) for i in range(5)]))
0,1,2,3,4
Brute force - non-pythonic
蛮力 - 非pythonic
The approach you suggest is one where a loop is used to concatenate a string adding commas along the way. Of course this produces the correct result but its much harder work.
您建议的方法是使用循环来连接字符串,并在此过程中添加逗号。当然,这会产生正确的结果,但它的工作要困难得多。
>>>iterable = range(5)
>>>result = ""
>>>for item, i in enumerate(iterable):
>>> result = result + str(item)
>>> if i > len(iterable) - 1:
>>> result = result + ","
>>>print(result)
0,1,2,3,4
回答by Anand S Kumar
You can use str.join()
and create the string you want to print and then print it. Example -
您可以使用str.join()
并创建要打印的字符串,然后打印它。例子 -
print(','.join([str(x) for x in range(5)]))
Demo -
演示 -
>>> print(','.join([str(x) for x in range(5)]))
0,1,2,3,4
I am using list comprehension above, as that is faster than generator expression , when used with str.join
.
我正在使用上面的列表理解,因为它比生成器表达式更快,当与str.join
.
回答by Rahul Gupta
To do that, you can use str.join()
.
为此,您可以使用str.join()
.
In [1]: print ','.join(map(str,range(5)))
0,1,2,3,4
We will need to convert the numbers in range(5)
to string first to call str.join()
. We do that using map()
operation. Then we join the list of strings obtained from map()
with a comma ,
.
我们需要range(5)
先将数字转换为字符串以调用str.join()
. 我们使用map()
操作来做到这一点。然后我们map()
用逗号连接从中获得的字符串列表,
。
回答by RufusVS
Another form you can use, closer to your original code:
您可以使用的另一种形式,更接近您的原始代码:
opt_comma="" # no comma on first print
for x in range(5):
print (opt_comma,x,sep="",end="") # we are manually handling sep and end
opt_comma="," # use comma for prints after the first one
print() # force new line
Of course, the intent of your program is probably better served by the other, more pythonic answers in this thread. Still, in some situations, this could be a useful method.
当然,您的程序的意图可能更适合该线程中的其他更pythonic 的答案。尽管如此,在某些情况下,这可能是一种有用的方法。