Python 在嵌套字符串列表上联接

Python 在嵌套字符串列表上联接,python,string,list,python-2.7,concatenation,Python,String,List,Python 2.7,Concatenation,我有一份清单: array = ['there is nothing','there is everything,',['there is','where']] 下面是一小段代码: str2 = "" for item in array: str2 += "".join(char for char in item) 其中: 'there is nothingthere is everything,there iswhere' 我怎么可能在外部列表和内部列表的每个项目之

我有一份清单:

array = ['there is nothing','there is everything,',['there is','where']]  
下面是一小段代码:

str2 = ""
for item in array:
    str2 += "".join(char for char in item)   
其中:

'there is nothingthere is everything,there iswhere'  
我怎么可能在外部列表和内部列表的每个项目之间添加一个空格

预期的输出字符串为:

'there is nothing there is everything, there is where'  
我提到了一些问题,尽管在我的案例中,这些力起了作用,但第一个问题给出了如下结果:

str2=""
lst = [' {}'.format(elem) for elem in array]
for item in lst:
    str2 += "".join(char for char in item)
输出

" there is nothing there is everything, ['there is', 'where']"  

第二个函数不适用于单词。

我将定义一个函数,它可以处理任意嵌套的字符串列表:

array = ['there is nothing','there is everything,',['there is','where']]

def concat_string(array):
    ret = ""
    for item in array:
        if isinstance(item,list):
            ret += concat_string(item)
        else:
            ret += item + " "

    return ret

print concat_string(array)

使用你的问题1,以下是一个通用但不是有效的解决方案。 1.为列表的所有元素添加空间 2.将它们与我们的小代码合并。 3.从两端修剪空间 4.删除可能已创建的重复空间

那么:

array = ['there is nothing','there is everything,',['there is','where']]
s = ''
for i in array:
    if isinstance(i, list):
        for j in i:
            s = ' '.join((s, j)) if s != '' else j
    else:
        s = ' '.join((s, i)) if s != '' else i
print(s)

我认为最好的方法是先将列表展平,然后按空格将它们连接起来

import collections
def flatten(foo):
    for x in foo:
        if isinstance(x, collections.Iterable) and not isinstance(x, str):
            for y in flatten(x):
                yield y
        else:
            yield x

my_sentence = " ".join(flatten(array))
或者,您可以将其用作所提到的单行解决方案,但它不适用于任意嵌套

In [1]: array = ['there is nothing','there is everything,',['there is','where']]

In [2]: " ".join([" ".join(s) if isinstance(s,list) else s for s in array])
Out[2]: 'there is nothing there is everything, there is where'
应该是:

array = ['there is nothing','there is everything,',['there is','where']]  
newstring = ''
for a in array :
    if type( a ) is str :
        newstring += a + " "
    else :
        newstring += ' '.join( a )
几乎可以是:
''.join([''.join(x)表示数组中的x])

您也可以使用三元:

array = ['there is nothing','there is everything,',['there is','where']]  
newstring = ''
for a in array :
    newstring += a + " " if type( a ) is str else ' '.join( a )

在str2+=''行的引号中加一个空格。join(项目中的字符对字符)不起作用,这是我做的第一件事,如果它起作用的话,这个问题会有十几个答案,还有几十个反对票,你可能没有机会发表评论,因为它现在就要结束了。预期的结果应该是:“什么都没有,什么都有,哪里都有”?这是一个简单测试用例的在线代码:“”。join([“”。join(s)如果isinstance(s,list)或(s代表数组中的s)),则它应该适用于它,但是,它不适用于任意嵌套。