[英]How do I turn a list of lists of words into a sentence string?
我有这个清单
[['obytay'], ['ikeslay'], ['ishay'], ['artway']]
我需要它看起来像
obytay ikeslay ishay artway
有人可以帮忙吗? 我尝试使用join
但我无法让它工作。
您在列表中有一个列表,因此它没有按照您认为的方式工作。 然而你的尝试是绝对正确的。 请按以下步骤操作:
' '.join(word[0] for word in word_list)
其中 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
它是一个字符串列表。 所以,你需要像这样用chain.from_iterable
字符串列表
from itertools import chain
print " ".join(chain.from_iterable(strings))
# obytay ikeslay ishay artway
如果我们首先将链式可迭代对象转换为列表,这将是有效的,就像这样
print " ".join(list(chain.from_iterable(strings)))
您也可以使用reduce
。
l = [['obytay'], ['ikeslay'], ['ishay'], ['artway']]
print " ".join(reduce(lambda a, b: a + b, l))
#'obytay ikeslay ishay artway'
def pig_latin(text): say = "" x=[] # Separate the text into words words = text.split() for word in words: # Create the pig latin word and add it to the list x.append(word[1:]+word[0]+'ay') for eachword in x: say += eachword+' ' # Turn the list back into a phrase return say print(pig_latin("hello how are you")) # Should be "ellohay owhay reaay ouyay" print(pig_latin("programming in python is fun")) # Should be "rogrammingpay niay ythonpay siay unfay"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.