如何在python中将long列表转换为逗号分隔的字符串[duplicate]

时间:2022-01-13 21:51:04

This question already has an answer here:

这个问题在这里已有答案:

I'm new to python, and have a list of longs which I want to join together into a comma separated string.

我是python的新手,并且有一个long列表,我想将它们连接成一个逗号分隔的字符串。

In PHP I'd do something like this:

在PHP中,我会做这样的事情:

$output = implode(",", $array)

In Python, I'm not sure how to do this. I've tried using join, but this doesn't work since the elements are the wrong type (i.e., not strings). Do I need to create a copy of the list and convert each element in the copy from a long into a string? Or is there a simpler way to do it?

在Python中,我不知道如何做到这一点。我尝试过使用join,但这不起作用,因为元素是错误的类型(即不是字符串)。我是否需要创建列表的副本并将副本中的每个元素从long转换为字符串?或者有更简单的方法吗?

5 个解决方案

#1


You have to convert the ints to strings and then you can join them:

你必须将int转换为字符串,然后你可以加入它们:

','.join([str(i) for i in list_of_ints])

#2


You can use map to transform a list, then join them up.

您可以使用map来转换列表,然后将它们连接起来。

",".join( map( str, list_of_things ) )

BTW, this works for any objects (not just longs).

顺便说一句,这适用于任何对象(不仅仅是长篇)。

#3


You can omit the square brackets from heikogerlach's answer since Python 2.5, I think:

从Python 2.5开始,你可以省略heikogerlach的答案中的方括号,我想:

','.join(str(i) for i in list_of_ints)

','。join(str(i)for list in list_of_ints)

This is extremely similar, but instead of building a (potentially large) temporary list of all the strings, it will generate them one at a time, as needed by the join function.

这非常相似,但它不是构建所有字符串的(可能很大的)临时列表,而是根据join函数的需要一次生成一个。

#4


Just for the sake of it, you can also use string formatting:

只是为了它,你也可以使用字符串格式:

",".join("{0}".format(i) for i in list_of_things)

#5


and yet another version more (pretty cool, eh?)

而另一个版本更多(非常酷,嗯?)

str(list_of_numbers)[1:-1]

#1


You have to convert the ints to strings and then you can join them:

你必须将int转换为字符串,然后你可以加入它们:

','.join([str(i) for i in list_of_ints])

#2


You can use map to transform a list, then join them up.

您可以使用map来转换列表,然后将它们连接起来。

",".join( map( str, list_of_things ) )

BTW, this works for any objects (not just longs).

顺便说一句,这适用于任何对象(不仅仅是长篇)。

#3


You can omit the square brackets from heikogerlach's answer since Python 2.5, I think:

从Python 2.5开始,你可以省略heikogerlach的答案中的方括号,我想:

','.join(str(i) for i in list_of_ints)

','。join(str(i)for list in list_of_ints)

This is extremely similar, but instead of building a (potentially large) temporary list of all the strings, it will generate them one at a time, as needed by the join function.

这非常相似,但它不是构建所有字符串的(可能很大的)临时列表,而是根据join函数的需要一次生成一个。

#4


Just for the sake of it, you can also use string formatting:

只是为了它,你也可以使用字符串格式:

",".join("{0}".format(i) for i in list_of_things)

#5


and yet another version more (pretty cool, eh?)

而另一个版本更多(非常酷,嗯?)

str(list_of_numbers)[1:-1]