我有一份清单清单:
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'
我提到了问题one和two,虽然这个问题在我的案例中起作用,但第一个问题是:
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']"
而第二个不适用于单词。
答案 0 :(得分:2)
我会定义一个可以处理任意嵌套字符串列表的函数:
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 :(得分:2)
怎么样:
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)
答案 2 :(得分:2)
我认为最好的方法是先将列表展平,然后按空格加入。
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))
或者,您可以使用@bhat irshad所述的单行解决方案,但它不适用于任意嵌套
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'
答案 3 :(得分:2)
应该是:
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) for x in array ] )
你也可以使用三元:
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 )
答案 4 :(得分:0)
使用您的问题1,以下将是一个通用但不是有效的解决方案。 1.为列表的所有元素添加空格 2.将它们与我们的小代码合并。 3.从两端修剪空格 4.删除可能已创建的重复空格。