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

前端 未结 4 1559
南旧
南旧 2021-02-07 00:17

I have this list

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

where I need it to look like

obytay ikeslay ishay ar         


        
相关标签:
4条回答
  • 2021-02-07 00:51
    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"
    
    0 讨论(0)
  • 2021-02-07 00:52

    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

    0 讨论(0)
  • 2021-02-07 00:59

    You can also use reduce.

    l = [['obytay'], ['ikeslay'], ['ishay'], ['artway']]
    print " ".join(reduce(lambda a, b: a + b, l))
    #'obytay ikeslay ishay artway'
    
    0 讨论(0)
  • 2021-02-07 01:13

    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)))
    
    0 讨论(0)
提交回复
热议问题