Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将嵌套的字符串列表展平为单个字符串_Python_String_List_Nested Lists - Fatal编程技术网

Python 将嵌套的字符串列表展平为单个字符串

Python 将嵌套的字符串列表展平为单个字符串,python,string,list,nested-lists,Python,String,List,Nested Lists,我正在尝试使用python将列表列表转换为单个字符串,我不想使用任何循环,我想在python中使用lambda来实现这一点,但没有得到期望的结果。 这是我的密码: #!/usr/bin/python import sys import math from functools import reduce def collapse(L): list = lambda L: [item for sublist in L for item in sublist] #sum(L, [])

我正在尝试使用python将列表列表转换为单个字符串,我不想使用任何循环,我想在python中使用lambda来实现这一点,但没有得到期望的结果。 这是我的密码:

#!/usr/bin/python
import sys
import math
from functools import reduce
def collapse(L):
    list = lambda L: [item for sublist in L for item in sublist]
    #sum(L, [])
    #print('"',*list,sep=' ')
    #whole_string = ''.join(list).replace(' ')
l=[ ["I","am"], ["trying", "to", "convert"], ["listoflist", "intoastring."]]
collapse(l)
print(*l,sep='')

我想要这样的输出:“我正在尝试将listoflist转换为Astring。”

看起来您误解了字符串操作的使用,因为它们都不适用。不会修改原始字符串,因为字符串是不可变的。您需要让函数返回一个值,然后将返回值赋回原始值

这里有一个使用
itertools.chain
的解决方案(您也可以用其他方法来实现,这只是简单明了):


试试这个:

>>> l=[ ["I","am"], ["trying", "to", "convert"], ["listoflist", "intoastring."]]
>>> 
>>> ' '.join([data for ele in l for data in ele])
'I am trying to convert listoflist intoastring.'

它对我有效

尝试了这个内部函数,但不起作用抱歉,但不要公然复制我答案中的人工制品。@Martjin Pieters它不是完全重复的。他忘了从
collapse
返回
,然后重新分配,不知道如何使用lambda。这个标题有误导性。@JulienD我意识到。。。。我现在的答案是这样的。
'I am trying to convert listoflist intoastring.'
>>> l=[ ["I","am"], ["trying", "to", "convert"], ["listoflist", "intoastring."]]
>>> 
>>> ' '.join([data for ele in l for data in ele])
'I am trying to convert listoflist intoastring.'