问题:您如何从字符串列表中创建逗号分隔的字符串?

您最好采用哪种方法来连接序列中的字符串,以便在每两个连续对之间添加一个逗号。也就是说,例如,您如何映射['a', 'b', 'c']'a,b,c'?(案例['s'][]应该分别映射到's'''。)

我通常最终会使用类似的东西''.join(map(lambda x: x+',',l))[:-1],但也会感到有些不满意。

What would be your preferred way to concatenate strings from a sequence such that between every two consecutive pairs a comma is added. That is, how do you map, for instance, ['a', 'b', 'c'] to 'a,b,c'? (The cases ['s'] and [] should be mapped to 's' and '', respectively.)

I usually end up using something like ''.join(map(lambda x: x+',',l))[:-1], but also feeling somewhat unsatisfied.


回答 0

my_list = ['a', 'b', 'c', 'd']
my_string = ','.join(my_list)
'a,b,c,d'

如果列表包含整数,则此方法无效


并且如果列表包含非字符串类型(例如整数,浮点数,布尔值,无),则请执行以下操作:

my_string = ','.join(map(str, my_list)) 
my_list = ['a', 'b', 'c', 'd']
my_string = ','.join(my_list)
'a,b,c,d'

This won’t work if the list contains integers


And if the list contains non-string types (such as integers, floats, bools, None) then do:

my_string = ','.join(map(str, my_list)) 

回答 1

为什么map/ lambda魔术?这不行吗?

>>> foo = ['a', 'b', 'c']
>>> print(','.join(foo))
a,b,c
>>> print(','.join([]))

>>> print(','.join(['a']))
a

如果列表中有数字,则可以使用列表理解:

>>> ','.join([str(x) for x in foo])

或生成器表达式:

>>> ','.join(str(x) for x in foo)

Why the map/lambda magic? Doesn’t this work?

>>> foo = ['a', 'b', 'c']
>>> print(','.join(foo))
a,b,c
>>> print(','.join([]))

>>> print(','.join(['a']))
a

In case if there are numbers in the list, you could use list comprehension:

>>> ','.join([str(x) for x in foo])

or a generator expression:

>>> ','.join(str(x) for x in foo)

回答 2

",".join(l)不适用于所有情况。我建议将CSV模块与StringIO一起使用

import StringIO
import csv

l = ['list','of','["""crazy"quotes"and\'',123,'other things']

line = StringIO.StringIO()
writer = csv.writer(line)
writer.writerow(l)
csvcontent = line.getvalue()
# 'list,of,"[""""""crazy""quotes""and\'",123,other things\r\n'

",".join(l) will not work for all cases. I’d suggest using the csv module with StringIO

import StringIO
import csv

l = ['list','of','["""crazy"quotes"and\'',123,'other things']

line = StringIO.StringIO()
writer = csv.writer(line)
writer.writerow(l)
csvcontent = line.getvalue()
# 'list,of,"[""""""crazy""quotes""and\'",123,other things\r\n'

回答 3

这是Python 3.0中允许非字符串列表项的替代解决方案:

>>> alist = ['a', 1, (2, 'b')]
  • 标准方式

    >>> ", ".join(map(str, alist))
    "a, 1, (2, 'b')"
  • 替代解决方案

    >>> import io
    >>> s = io.StringIO()
    >>> print(*alist, file=s, sep=', ', end='')
    >>> s.getvalue()
    "a, 1, (2, 'b')"

注意:逗号后的空格是故意的。

Here is a alternative solution in Python 3.0 which allows non-string list items:

>>> alist = ['a', 1, (2, 'b')]
  • a standard way

    >>> ", ".join(map(str, alist))
    "a, 1, (2, 'b')"
    
  • the alternative solution

    >>> import io
    >>> s = io.StringIO()
    >>> print(*alist, file=s, sep=', ', end='')
    >>> s.getvalue()
    "a, 1, (2, 'b')"
    

NOTE: The space after comma is intentional.


回答 4

你不只是想要:

",".join(l)

显然,如果您需要在值中引用/转义逗号等,它将变得更加复杂。在这种情况下,我建议您查看标准库中的csv模块:

https://docs.python.org/library/csv.html

Don’t you just want:

",".join(l)

Obviously it gets more complicated if you need to quote/escape commas etc in the values. In that case I would suggest looking at the csv module in the standard library:

https://docs.python.org/library/csv.html


回答 5

彼得·霍夫曼(Peter Hoffmann)

使用生成器表达式的好处是还可以生成迭代器,但可以节省导入itertools的时间。此外,列表推导通常首选映射,因此,我希望生成器表达式比imap首选。

>>> l = [1, "foo", 4 ,"bar"]
>>> ",".join(str(bit) for bit in l)
'1,foo,4,bar' 

@Peter Hoffmann

Using generator expressions has the benefit of also producing an iterator but saves importing itertools. Furthermore, list comprehensions are generally preferred to map, thus, I’d expect generator expressions to be preferred to imap.

>>> l = [1, "foo", 4 ,"bar"]
>>> ",".join(str(bit) for bit in l)
'1,foo,4,bar' 

回答 6

>>> my_list = ['A', '', '', 'D', 'E',]
>>> ",".join([str(i) for i in my_list if i])
'A,D,E'

my_list可以包含任何类型的变量。这样可以避免结果'A,,,D,E'

>>> my_list = ['A', '', '', 'D', 'E',]
>>> ",".join([str(i) for i in my_list if i])
'A,D,E'

my_list may contain any type of variables. This avoid the result 'A,,,D,E'.


回答 7

l=['a', 1, 'b', 2]

print str(l)[1:-1]

Output: "'a', 1, 'b', 2"
l=['a', 1, 'b', 2]

print str(l)[1:-1]

Output: "'a', 1, 'b', 2"

回答 8

使用列表推导的@ jmanning2k不利于创建新的临时列表。更好的解决方案是使用itertools.imap返回一个迭代器

from itertools import imap
l = [1, "foo", 4 ,"bar"]
",".join(imap(str, l))

@jmanning2k using a list comprehension has the downside of creating a new temporary list. The better solution would be using itertools.imap which returns an iterator

from itertools import imap
l = [1, "foo", 4 ,"bar"]
",".join(imap(str, l))

回答 9

这是清单的例子

>>> myList = [['Apple'],['Orange']]
>>> myList = ','.join(map(str, [i[0] for i in myList])) 
>>> print "Output:", myList
Output: Apple,Orange

更准确的:-

>>> myList = [['Apple'],['Orange']]
>>> myList = ','.join(map(str, [type(i) == list and i[0] for i in myList])) 
>>> print "Output:", myList
Output: Apple,Orange

示例2:

myList = ['Apple','Orange']
myList = ','.join(map(str, myList)) 
print "Output:", myList
Output: Apple,Orange

Here is an example with list

>>> myList = [['Apple'],['Orange']]
>>> myList = ','.join(map(str, [i[0] for i in myList])) 
>>> print "Output:", myList
Output: Apple,Orange

More Accurate:-

>>> myList = [['Apple'],['Orange']]
>>> myList = ','.join(map(str, [type(i) == list and i[0] for i in myList])) 
>>> print "Output:", myList
Output: Apple,Orange

Example 2:-

myList = ['Apple','Orange']
myList = ','.join(map(str, myList)) 
print "Output:", myList
Output: Apple,Orange

回答 10

我要说的csv是,库是这里唯一明智的选择,因为它是为应对所有csv用例(例如字符串中的逗号)而构建的。

要将列表输出l到.csv文件,请执行以下操作:

import csv
with open('some.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(l)  # this will output l as a single row.  

也可以用于writer.writerows(iterable)将多行输出到csv。

此示例与Python 3兼容,此处使用的另一个答案StringIO是Python 2。

I would say the csv library is the only sensible option here, as it was built to cope with all csv use cases such as commas in a string, etc.

To output a list l to a .csv file:

import csv
with open('some.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(l)  # this will output l as a single row.  

It is also possible to use writer.writerows(iterable) to output multiple rows to csv.

This example is compatible with Python 3, as the other answer here used StringIO which is Python 2.


回答 11

除非我缺少任何东西,否则','.join(foo)应该做您所要的。

>>> ','.join([''])
''
>>> ','.join(['s'])
's'
>>> ','.join(['a','b','c'])
'a,b,c'

(编辑:正如jmanning2k指出的那样,

','.join([str(x) for x in foo])

是更安全且相当Pythonic的,尽管如果元素可以包含逗号,则生成的字符串将很难解析-那时,您需要csv模块的全部功能,正如Douglas在他的回答中指出的那样。)

Unless I’m missing something, ','.join(foo) should do what you’re asking for.

>>> ','.join([''])
''
>>> ','.join(['s'])
's'
>>> ','.join(['a','b','c'])
'a,b,c'

(edit: and as jmanning2k points out,

','.join([str(x) for x in foo])

is safer and quite Pythonic, though the resulting string will be difficult to parse if the elements can contain commas — at that point, you need the full power of the csv module, as Douglas points out in his answer.)


回答 12

我的两分钱。我喜欢更简单的python单行代码:

>>> from itertools import imap, ifilter
>>> l = ['a', '', 'b', 1, None]
>>> ','.join(imap(str, ifilter(lambda x: x, l)))
a,b,1
>>> m = ['a', '', None]
>>> ','.join(imap(str, ifilter(lambda x: x, m)))
'a'

这是pythonic,适用于字符串,数字,无和空字符串。它很短并且满足要求。如果列表中不包含数字,则可以使用以下更简单的变体:

>>> ','.join(ifilter(lambda x: x, l))

同样,该解决方案不会创建新列表,而是使用迭代器,如@Peter Hoffmann指出的(谢谢)。

My two cents. I like simpler an one-line code in python:

>>> from itertools import imap, ifilter
>>> l = ['a', '', 'b', 1, None]
>>> ','.join(imap(str, ifilter(lambda x: x, l)))
a,b,1
>>> m = ['a', '', None]
>>> ','.join(imap(str, ifilter(lambda x: x, m)))
'a'

It’s pythonic, works for strings, numbers, None and empty string. It’s short and satisfies the requirements. If the list is not going to contain numbers, we can use this simpler variation:

>>> ','.join(ifilter(lambda x: x, l))

Also this solution doesn’t create a new list, but uses an iterator, like @Peter Hoffmann pointed (thanks).


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。