简体   繁体   中英

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

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 join but I can't get it to work.

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 = [['obytay'], ['ikeslay'], ['ishay'], ['artway']]
>>> print ' '.join(word[0] for word in word_list)
obytay ikeslay ishay artway

Tobey likes his wart

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

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)))

You can also use 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM