从一个序列中连接字符串,使每两个连续的对之间添加一个逗号,您的首选方法是什么?也就是说,你如何映射,例如,['a', 'b', 'c']到'a,b,c'?(case ['s']和[]应该分别映射为's'和''。)
我通常会用“。”Join (map(lambda x: x+',',l))[:-1],但也感到有些不满意。
从一个序列中连接字符串,使每两个连续的对之间添加一个逗号,您的首选方法是什么?也就是说,你如何映射,例如,['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')"
恩乔伊特
my_list = ['a', 'b', 'c', 'd']
my_string = ','.join(my_list)
'a,b,c,d'
如果列表包含整数,这将不起作用
如果列表包含非字符串类型(如整数、浮点数、bool、None),则执行以下操作:
my_string = ','.join(map(str, my_list))
如果你想做快捷方式:):
','.join([str(word) for word in wordList])
但如果你想用逻辑来炫耀:):
wordList = ['USD', 'EUR', 'JPY', 'NZD', 'CHF', 'CAD']
stringText = ''
for word in wordList:
stringText += word + ','
stringText = stringText[:-2] # get rid of last comma
print(stringText)
",".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'
我想说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。