单行不带括号的打印列表

问题:单行不带括号的打印列表

我在Python中有一个列表

names = ["Sam", "Peter", "James", "Julian", "Ann"]

我想在没有正常的“ []的情况下在单行中打印数组

names = ["Sam", "Peter", "James", "Julian", "Ann"]
print (names)

将给出的输出为;

["Sam", "Peter", "James", "Julian", "Ann"]

那不是我想要的格式,而是我希望它像这样;

Sam, Peter, James, Julian, Ann

注意:它必须在一行中。

I have a list in Python e.g.

names = ["Sam", "Peter", "James", "Julian", "Ann"]

I want to print the array in a single line without the normal ” []

names = ["Sam", "Peter", "James", "Julian", "Ann"]
print (names)

Will give the output as;

["Sam", "Peter", "James", "Julian", "Ann"]

That is not the format I want instead I want it to be like this;

Sam, Peter, James, Julian, Ann

Note: It must be in a single row.


回答 0

print(', '.join(names))

听起来很简单,它只接受列表中的所有元素,然后将它们加入', '

print(', '.join(names))

This, like it sounds, just takes all the elements of the list and joins them with ', '.


回答 1

这是一个简单的例子。

names = ["Sam", "Peter", "James", "Julian", "Ann"]
print(*names, sep=", ")

星标将列表解压缩并返回列表中的每个元素。

Here is a simple one.

names = ["Sam", "Peter", "James", "Julian", "Ann"]
print(*names, sep=", ")

the star unpacks the list and return every element in the list.


回答 2

通用解决方案,适用于非字符串数组:

>>> print str(names)[1:-1]
'Sam', 'Peter', 'James', 'Julian', 'Ann'

General solution, works on arrays of non-strings:

>>> print str(names)[1:-1]
'Sam', 'Peter', 'James', 'Julian', 'Ann'

回答 3

如果输入数组是Integer类型,则需要先将数组转换为字符串类型 array,然后使用join方法与所需的空间连接,或分隔。例如:

>>> arr = [1, 2, 4, 3]
>>> print(", " . join(arr))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, int found
>>> sarr = [str(a) for a in arr]
>>> print(", " . join(sarr))
1, 2, 4, 3
>>>

直接使用join来连接整数和字符串将抛出错误,如上所示。

If the input array is Integer type then you need to first convert array into string type array and then use join method for joining with , or space whatever you want. e.g:

>>> arr = [1, 2, 4, 3]
>>> print(", " . join(arr))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, int found
>>> sarr = [str(a) for a in arr]
>>> print(", " . join(sarr))
1, 2, 4, 3
>>>

Direct using of join which will join the integer and string will throw error as show above.


回答 4

有两个答案,首先是使用“ sep”设置

>>> print(*names, sep = ', ')

另一个在下面

>>> print(', '.join(names))

There are two answers , First is use ‘sep’ setting

>>> print(*names, sep = ', ')

The other is below

>>> print(', '.join(names))

回答 5

这就是你所需要的

", ".join(names)

This is what you need

", ".join(names)

回答 6

','.join(list)仅当列表中的所有项目均为字符串时,该选项才有效。如果您希望将数字列表转换为逗号分隔的字符串。例如a = [1, 2, 3, 4]进入,'1,2,3,4'则可以

str(a)[1:-1] # '1, 2, 3, 4'

要么

str(a).lstrip('[').rstrip(']') # '1, 2, 3, 4'

尽管这不会删除任何嵌套列表。

将其转换回列表

a = '1,2,3,4'
import ast
ast.literal_eval('['+a+']')
#[1, 2, 3, 4]

','.join(list) will work only if all the items in the list are strings. If you are looking to convert a list of numbers to a comma separated string. such as a = [1, 2, 3, 4] into '1,2,3,4' then you can either

str(a)[1:-1] # '1, 2, 3, 4'

or

str(a).lstrip('[').rstrip(']') # '1, 2, 3, 4'

although this won’t remove any nested list.

To convert it back to a list

a = '1,2,3,4'
import ast
ast.literal_eval('['+a+']')
#[1, 2, 3, 4]

回答 7

您需要遍历列表并将end=" "其保持在一行上

names = ["Sam", "Peter", "James", "Julian", "Ann"]
    index=0
    for name in names:
        print(names[index], end=", ")
        index += 1

You need to loop through the list and use end=" "to keep it on one line

names = ["Sam", "Peter", "James", "Julian", "Ann"]
    index=0
    for name in names:
        print(names[index], end=", ")
        index += 1

回答 8

打印(*名称)

如果您希望将它们以空格分隔的形式打印出来,那么它将在python 3中起作用。如果您需要逗号或介于两者之间的其他内容,请继续使用.join()解决方案

print(*names)

this will work in python 3 if you want them to be printed out as space separated. If you need comma or anything else in between go ahead with .join() solution


回答 9

我不知道这是否像其他方法一样有效,但是简单的逻辑总是有效:

import sys
name = ["Sam", "Peter", "James", "Julian", "Ann"]
for i in range(0, len(names)):
    sys.stdout.write(names[i])
    if i != len(names)-1:
        sys.stdout.write(", ")

输出:

山姆,彼得,詹姆斯,朱利安·安

I don’t know if this is efficient as others but simple logic always works:

import sys
name = ["Sam", "Peter", "James", "Julian", "Ann"]
for i in range(0, len(names)):
    sys.stdout.write(names[i])
    if i != len(names)-1:
        sys.stdout.write(", ")

Output:

Sam, Peter, James, Julian, Ann


回答 10

以下函数将接收列表并返回列表项的字符串。然后可以将其用于记录或打印目的。

def listToString(inList):
    outString = ''
    if len(inList)==1:
        outString = outString+str(inList[0])
    if len(inList)>1:
        outString = outString+str(inList[0])
        for items in inList[1:]:
            outString = outString+', '+str(items)
    return outString

The following function will take in a list and return a string of the lists’ items. This can then be used for logging or printing purposes.

def listToString(inList):
    outString = ''
    if len(inList)==1:
        outString = outString+str(inList[0])
    if len(inList)>1:
        outString = outString+str(inList[0])
        for items in inList[1:]:
            outString = outString+', '+str(items)
    return outString