What would be your preferred way to concatenate strings from a sequence such that between each two consecutive pair 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.)
从序列中连接字符串的首选方法是什么,以便在每个连续的对之间添加一个逗号。也就是说,你如何映射,例如,[a,b,c]到a,b,c ?(case [s]和[]应该分别映射到s和"。)
I usually end up using something like ''.join(map(lambda x: x+',',l))[:-1]
, but also feeling somewhat unsatisfied.
我通常会用“”之类的词。连接(map(x: x+',',l))[:-1],但也感觉有些不满足。
Edit: I'm both ashamed and happy that the solution is so simple. Obviously I have hardly a clue as to what I'm doing. (I probably needed "simple" concatenation in the past and somehow memorised s.join([e1,e2,...])
as a shorthand for s+e1+e2+...
.)
编辑:我既羞愧又高兴,因为解决方案如此简单。很明显,我对自己在做什么一无所知。(我可能需要“简单”连接过去和不知何故记s.join((e1,e2,…)),简称s + e1 + e2 + ....)
15 个解决方案
#1
601
myList = ['a','b','c','d']
myString = ",".join(myList )
This won't work if the list contains numbers.
如果列表包含数字,这将不起作用。
As Ricardo Reyes suggested, if it contains non-string types (such as integers, floats, bools, None) then do:
正如Ricardo Reyes所建议的,如果它包含非字符串类型(如整数、浮点数、bools、None),则应:
myList = ','.join(map(str, myList))
#2
58
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
Edit: @mark-biek points out the case for numbers. Perhaps the list comprehension:
编辑:@mark-biek指出了数字的情况。也许理解列表:
>>>','.join([str(x) for x in foo])
is more "pythonic".
“神谕的”。
Edit2: Thanks for the suggestions. I'll use the generator rather than the list comprehension in the future.
Edit2:谢谢你的建议。以后我将使用生成器而不是列表理解。
>>>','.join(str(x) for x in foo)
#3
11
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:
显然,如果需要在值中引用/转义逗号,就会变得更加复杂。在这种情况下,我建议查看标准库中的csv模块:
https://docs.python.org/library/csv.html
https://docs.python.org/library/csv.html
#4
10
Here is a alternative solution in Python 3.0 which allows non-string list items:
下面是Python 3.0中的另一种解决方案,它允许非字符串列表项:
>>> 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.
注意:逗号后面的空格是故意的。
#5
10
",".join(l)
will not work for all cases. I'd suggest using the csv module with StringIO
join(l)并不适用于所有的情况。我建议使用带有StringIO的csv模块
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'
#6
9
@Peter Hoffmann
@Peter霍夫曼
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.
使用生成器表达式的好处是还可以生成迭代器,但可以节省导入迭代工具。此外,列表理解通常更倾向于映射,因此,我希望生成器表达式优于imap。
>>> l = [1, "foo", 4 ,"bar"]
>>> ",".join(str(bit) for bit in l)
'1,foo,4,bar'
#7
4
@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
@jmanning2k使用列表理解有创建新临时列表的缺点。更好的解决方案是使用迭代工具。返回迭代器的imap
from itertools import imap
l = [1, "foo", 4 ,"bar"]
",".join(imap(str, l))
#8
4
>>> 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'
.
my_list可能包含任何类型的变量。这样就避免了“A, D,E”的结果。
#9
3
for converting list containing numbers do the following:
要转换包含数字的列表,请执行以下操作:
string = ''.join([str(i) for i in list])
#10
3
l=['a', 1, 'b', 2]
print str(l)[1:-1]
Output: "'a', 1, 'b', 2"
#11
1
Unless I'm missing something, ','.join(foo)
should do what you're asking for.
除非我遗漏了什么,否则,.join(foo)应该按照你的要求去做。
>>> ','.join([''])
''
>>> ','.join(['s'])
's'
>>> ','.join(['a','b','c'])
'a,b,c'
(edit: and as jmanning2k points out,
(编辑:正如jmanning2k指出,
','.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.)
更安全、更python化,尽管如果元素可以包含逗号,那么产生的字符串将难以解析——此时,您需要csv模块的全部功能,正如Douglas在其回答中所指出的那样。)
#12
0
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:-
示例2:
myList = ['Apple','Orange']
myList = ','.join(map(str, myList))
print "Output:", myList
Output: Apple,Orange
#13
0
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.
我想说csv库是这里唯一明智的选择,因为它是用来处理所有的csv用例的,比如字符串中的逗号等等。
To output a list l
to a .csv file:
将列表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.
It is also possible to use writer.writerows(iterable)
to output multiple rows to csv.
也可以使用writer.writerows(iterable)将多行输出到csv。
This example is compatible with Python 3, as the other answer here used StringIO
which is Python 2.
这个示例与Python 3兼容,因为这里的另一个答案使用的是Python 2的StringIO。
#14
-1
just a little something like this :)
就像这样:
String = "Once:Upon:a:Time:A:Long:Time:Ago"
ding = String.split(':')
ring = (" , ").join(ding)
print(ring)
Output: Once , Upon , a , Time , A , Long , Time , Ago
输出:Once, Upon, a, Time, a, Long, Time, Ago
#15
-2
My two cents. I like simpler an one-line code in python:
我的两个美分。我喜欢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:
它是python语言的,适用于字符串,数字,无和空字符串。它很短,满足要求。如果列表中不包含数字,我们可以使用更简单的变体:
>>> ','.join(ifilter(lambda x: x, l))
Also this solution doesn't create a new list, but uses an iterator, like @Peter Hoffmann pointed (thanks).
此外,该解决方案不创建新的列表,而是使用迭代器,如@Peter Hoffmann所指出的(谢谢)。
#1
601
myList = ['a','b','c','d']
myString = ",".join(myList )
This won't work if the list contains numbers.
如果列表包含数字,这将不起作用。
As Ricardo Reyes suggested, if it contains non-string types (such as integers, floats, bools, None) then do:
正如Ricardo Reyes所建议的,如果它包含非字符串类型(如整数、浮点数、bools、None),则应:
myList = ','.join(map(str, myList))
#2
58
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
Edit: @mark-biek points out the case for numbers. Perhaps the list comprehension:
编辑:@mark-biek指出了数字的情况。也许理解列表:
>>>','.join([str(x) for x in foo])
is more "pythonic".
“神谕的”。
Edit2: Thanks for the suggestions. I'll use the generator rather than the list comprehension in the future.
Edit2:谢谢你的建议。以后我将使用生成器而不是列表理解。
>>>','.join(str(x) for x in foo)
#3
11
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:
显然,如果需要在值中引用/转义逗号,就会变得更加复杂。在这种情况下,我建议查看标准库中的csv模块:
https://docs.python.org/library/csv.html
https://docs.python.org/library/csv.html
#4
10
Here is a alternative solution in Python 3.0 which allows non-string list items:
下面是Python 3.0中的另一种解决方案,它允许非字符串列表项:
>>> 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.
注意:逗号后面的空格是故意的。
#5
10
",".join(l)
will not work for all cases. I'd suggest using the csv module with StringIO
join(l)并不适用于所有的情况。我建议使用带有StringIO的csv模块
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'
#6
9
@Peter Hoffmann
@Peter霍夫曼
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.
使用生成器表达式的好处是还可以生成迭代器,但可以节省导入迭代工具。此外,列表理解通常更倾向于映射,因此,我希望生成器表达式优于imap。
>>> l = [1, "foo", 4 ,"bar"]
>>> ",".join(str(bit) for bit in l)
'1,foo,4,bar'
#7
4
@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
@jmanning2k使用列表理解有创建新临时列表的缺点。更好的解决方案是使用迭代工具。返回迭代器的imap
from itertools import imap
l = [1, "foo", 4 ,"bar"]
",".join(imap(str, l))
#8
4
>>> 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'
.
my_list可能包含任何类型的变量。这样就避免了“A, D,E”的结果。
#9
3
for converting list containing numbers do the following:
要转换包含数字的列表,请执行以下操作:
string = ''.join([str(i) for i in list])
#10
3
l=['a', 1, 'b', 2]
print str(l)[1:-1]
Output: "'a', 1, 'b', 2"
#11
1
Unless I'm missing something, ','.join(foo)
should do what you're asking for.
除非我遗漏了什么,否则,.join(foo)应该按照你的要求去做。
>>> ','.join([''])
''
>>> ','.join(['s'])
's'
>>> ','.join(['a','b','c'])
'a,b,c'
(edit: and as jmanning2k points out,
(编辑:正如jmanning2k指出,
','.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.)
更安全、更python化,尽管如果元素可以包含逗号,那么产生的字符串将难以解析——此时,您需要csv模块的全部功能,正如Douglas在其回答中所指出的那样。)
#12
0
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:-
示例2:
myList = ['Apple','Orange']
myList = ','.join(map(str, myList))
print "Output:", myList
Output: Apple,Orange
#13
0
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.
我想说csv库是这里唯一明智的选择,因为它是用来处理所有的csv用例的,比如字符串中的逗号等等。
To output a list l
to a .csv file:
将列表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.
It is also possible to use writer.writerows(iterable)
to output multiple rows to csv.
也可以使用writer.writerows(iterable)将多行输出到csv。
This example is compatible with Python 3, as the other answer here used StringIO
which is Python 2.
这个示例与Python 3兼容,因为这里的另一个答案使用的是Python 2的StringIO。
#14
-1
just a little something like this :)
就像这样:
String = "Once:Upon:a:Time:A:Long:Time:Ago"
ding = String.split(':')
ring = (" , ").join(ding)
print(ring)
Output: Once , Upon , a , Time , A , Long , Time , Ago
输出:Once, Upon, a, Time, a, Long, Time, Ago
#15
-2
My two cents. I like simpler an one-line code in python:
我的两个美分。我喜欢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:
它是python语言的,适用于字符串,数字,无和空字符串。它很短,满足要求。如果列表中不包含数字,我们可以使用更简单的变体:
>>> ','.join(ifilter(lambda x: x, l))
Also this solution doesn't create a new list, but uses an iterator, like @Peter Hoffmann pointed (thanks).
此外,该解决方案不创建新的列表,而是使用迭代器,如@Peter Hoffmann所指出的(谢谢)。