如何在python上进行列表的逗号分隔打印

2024-04-25 13:18:24 发布

您现在位置:Python中文网/ 问答频道 /正文

在python上用逗号分隔打印列表最干净的方法是什么。你知道吗

I have list: [1,2,3,4]

I need: "1, 2, 3, 4"

Tags: 方法列表haveneedlist逗号
3条回答

你可以在这条线上做点什么。你知道吗

mylist = [1,2,3,4,5] 
m = map(str, mylist) # map function to convert each item in the list to a string 
j = ', '.join(m) # join to combine those strings with ', '
print (j)

您可以尝试使用mapstr方法应用于所有要将int转换为str的项,然后使用join方法连接列表:

string.join

Concatenate a list or tuple of words with intervening occurrences of sep.

a=[1,2,3,4]

print ",".join(map(str,a))

输出:

1,2,3,4

唯一不寻常的部分是...,不幸的是strrepr都变成了'Ellipsis'。其他答案不能正确处理,但这个答案:

>>> a = [1, 2, 3, 4, ...]
>>> print(', '.join('...' if x is ... else str(x) for x in a))
1, 2, 3, 4, ...

编辑:这是原来的问题,在它被改变之前(尽管它仍然有效)。你知道吗

相关问题 更多 >