从一个序列中连接字符串,使每两个连续的对之间添加一个逗号,您的首选方法是什么?也就是说,你如何映射,例如,['a', 'b', 'c']到'a,b,c'?(case ['s']和[]应该分别映射为's'和''。)

我通常会用“。”Join (map(lambda x: x+',',l))[:-1],但也感到有些不满意。


当前回答

下面是一个带有列表的例子

>>> 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

其他回答

mmm还需要SQL是:

l = ["foo" , "baar" , 6]
where_clause = "..... IN ("+(','.join([ f"'{x}'" for x in l]))+")"
>> "..... IN ('foo','baar','6')"

恩乔伊特

@jmanning2k使用列表推导的缺点是创建一个新的临时列表。更好的解决方案是使用itertools。Imap返回一个迭代器

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

print str(l)[1:-1]

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

",".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'
my_list = ['a', 'b', 'c', 'd']
my_string = ','.join(my_list)
'a,b,c,d'

如果列表包含整数,这将不起作用


如果列表包含非字符串类型(如整数、浮点数、bool、None),则执行以下操作:

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