Python 从列表创建逗号分隔的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24557809/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:46:57  来源:igfitidea点击:

Creating comma-separated string from list

pythonstringlistjoin

提问by Karnivaurus

I have a list of ints and want to create a comma-separated string. The following:

我有一个整数列表,想创建一个逗号分隔的字符串。下列:

x = [3, 1, 4, 1, 5]
y = ",".join(x)

Give the error:

给出错误:

TypeError: sequence item 0: expected string, int found

How do I create the string? I could manually convert every element from int to string, insert this into a new list, and then do the join on this new list, but I'm wondering if there is a cleaner solution.

如何创建字符串?我可以手动将每个元素从 int 转换为字符串,将其插入到一个新列表中,然后在这个新列表上进行连接,但我想知道是否有更简洁的解决方案。

采纳答案by Karnivaurus

str.joinonly accepts an iterable of strings, not one of integers. From the docs:

str.join只接受一个可迭代的字符串,而不是一个整数。从文档

str.join(iterable)

Return a string which is the concatenation of the stringsin the iterable iterable.

str.join(iterable)

返回一个字符串,它是iterable 中字符串的串联iterable

Thus, you need to convert the items in xinto strings. You can use either mapor a list comprehension:

因此,您需要将项目转换x为字符串。您可以使用map列表理解

x = [3, 1, 4, 1, 5]
y = ",".join(map(str, x))

x = [3, 1, 4, 1, 5]
y = ",".join([str(item) for item in x])

See a demonstration below:

请参阅下面的演示:

>>> x = [3, 1, 4, 1, 5]
>>>
>>> ",".join(map(str, x))
'3,1,4,1,5'
>>>
>>> ",".join([str(item) for item in x])
'3,1,4,1,5'
>>>

回答by ueg1990

Just modify the argument to joinso that each element is converted to a string:

只需修改参数,join以便将每个元素转换为字符串:

x = [3, 1, 4, 1, 5]
y = ",".join(str(i) for i in x)

回答by dawg

If you are dealing with a csv file that is something other than the trivial example here, please do remember you are better off using the csv moduleto read and write csv, since CSV can be surprisingly complex.

如果您正在处理的 csv 文件不是这里的简单示例,请记住最好使用csv 模块来读取和写入 csv,因为CSV 可能非常复杂

Here is a write example:

这是一个写入示例:

import csv

x = [['Header\n1', 'H 2', 'H 3', 'H, 4'],[1,2,3,4],[5,6,7,8],[9,10,11,12]]

with open('/tmp/test.csv', 'w') as fout:
    writer=csv.writer(fout)
    for l in x:
        writer.writerow(l)

Note the embedded comma in 'H, 4'and the embedded new line in 'Header\n1'that may trip up efforts to decode if not properly encoded.

请注意嵌入的逗号'H, 4'和嵌入的新行,'Header\n1'如果编码不正确,可能会妨碍解码。

The file 'test.csv' that the csv module produces:

csv 模块生成的文件“test.csv”:

"Header
1",H 2,H 3,"H, 4"
1,2,3,4
5,6,7,8
9,10,11,12

Note the quoting around "Header\n1"and "H, 4"` in the file so that the csv is correctly decoded in the future.

请注意文件中的引号"Header\n1"和“H, 4”`,以便将来正确解码 csv。

Now check you can read that back:

现在检查你可以读回:

with open('/tmp/test.csv') as f:
    csv_in=[[int(e) if e.isdigit() else e for e in row] 
               for row in csv.reader(f)]

>>> csv_in==x
True

Just sayin' You are usually better off using the tools in the library for csv.

只是说'您通常最好使用 csv 库中的工具。