gpt4 book ai didi

python - 加入嵌套的字符串列表

转载 作者:行者123 更新时间:2023-11-28 20:21:45 24 4
gpt4 key购买 nike

我有一个列表列表:

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'  

我提到问题onetwo ,虽然这对我来说很有效,但第一个给出了类似的东西:

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']"  

第二个不适用于单词。

最佳答案

我认为最好的方法是先将列表展平,然后按空格加入它们。

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'

关于python - 加入嵌套的字符串列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26574948/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com