1

I am trying to convert a list of list into a single string using python and I don't want to use any loops I want to do it using lambda in Python but not getting the desired result. here is my code:

#!/usr/bin/python
import sys
import math
from functools import reduce
def collapse(L):
    list = lambda L: [item for sublist in L for item in sublist]
    #sum(L, [])
    #print('"',*list,sep=' ')
    #whole_string = ''.join(list).replace(' ')
l=[ ["I","am"], ["trying", "to", "convert"], ["listoflist", "intoastring."]]
collapse(l)
print(*l,sep='')

I want an output like this "I am trying to convert listoflist intoastring."

cs95
  • 379,657
  • 97
  • 704
  • 746
Deepesh Meena
  • 135
  • 1
  • 13
  • @Martjin Pieters It is not completely a duplicate. He forgot to `return` from `collapse`, to reassign after it, and doesn't know how to use a lambda. The title is misleading. – JulienD Sep 07 '17 at 11:31
  • @JulienD I realised that.... It's in my answer now. – cs95 Sep 07 '17 at 11:36

2 Answers2

3

It looks like you're misunderstanding the use of the string operations in the sense that none of them work in-place. The original string is not modified, because strings are immutable. You will need to have your function return a value, and then assign the return value back to the original.

Here's a solution using itertools.chain (you can do it other ways too, this is just concise):

from itertools import chain

def collapse(lst):
    return ' ' .join(chain.from_iterable(lst))

out = collapse([["I","am"], ["trying", "to", "convert"], ["listoflist", "intoastring."]])
print(out) 

'I am trying to convert listoflist intoastring.'
cs95
  • 379,657
  • 97
  • 704
  • 746
-2

Try this:

>>> l=[ ["I","am"], ["trying", "to", "convert"], ["listoflist", "intoastring."]]
>>> 
>>> ' '.join([data for ele in l for data in ele])
'I am trying to convert listoflist intoastring.'

Its working for me

cs95
  • 379,657
  • 97
  • 704
  • 746
Nirmi
  • 356
  • 3
  • 11