Python 如何将单词列表转换为句子字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22741526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:34:43  来源:igfitidea点击:

How do I turn a list of words into a sentence string?

python

提问by user3477556

I have this list

我有这个清单

[['obytay'], ['ikeslay'], ['ishay'], ['artway']]

where I need it to look like

我需要它看起来像

obytay ikeslay ishay artway

Can anybody help? I tried using joinbut I can't get it to work.

有人可以帮忙吗?我尝试使用join但我无法让它工作。

采纳答案by sshashank124

You have a list in a list so its not working the way you think it should. Your attempt however was absolutely right. Do it as follows:

您在列表中有一个列表,因此它没有按照您认为的方式工作。然而你的尝试是绝对正确的。请按以下步骤操作:

' '.join(word[0] for word in word_list)

where word_list is your list shown above.

其中 word_list 是上面显示的列表。

>>> word_list = [['obytay'], ['ikeslay'], ['ishay'], ['artway']]
>>> print ' '.join(word[0] for word in word_list)
obytay ikeslay ishay artway

Tobey likes his wart

Tobey likes his wart

回答by thefourtheye

It is a list of strings. So, you need to chain the list of strings, with chain.from_iterablelike this

它是一个字符串列表。所以,你需要chain.from_iterable像这样链接字符串列表

from itertools import chain
print " ".join(chain.from_iterable(strings))
# obytay ikeslay ishay artway

It will be efficient if we first convert the chained iterable to a list, like this

如果我们首先将链式可迭代对象转换为列表,这将是有效的,就像这样

print " ".join(list(chain.from_iterable(strings)))

回答by Kei Minagawa

You can also use reduce.

您也可以使用reduce.

l = [['obytay'], ['ikeslay'], ['ishay'], ['artway']]
print " ".join(reduce(lambda a, b: a + b, l))
#'obytay ikeslay ishay artway'