Home > Software design >  Change Sub lists into one string
Change Sub lists into one string

Time:05-29

I have the following

[1, 3, 14, 26, 59, 535] [932, 462, 97, 38, 8] [3, 3, 64, 83] [288, 279, 50] [4, 19] [716] [9, 939, 37510]

that I wish to change into

1 3 14 26 59 535 932 462 97 38 8 3 3 64 83 288 279 50 4 19 716 9 939 37510

is there any quick fix?

I have already tried joining (' '.join(str(e) for e in result))

CodePudding user response:

It is possible to do this with a plain python comprehension

result = [[1, 3, 14, 26, 59, 535], [932, 462, 97, 38, 8], [3, 3, 64, 83], [288, 279, 50], [4, 19], [716], [9, 939, 37510]]

' '.join(str(n) for sublist in result for n in sublist)

Which will give you the string:

'1 3 14 26 59 535 932 462 97 38 8 3 3 64 83 288 279 50 4 19 716 9 939 37510'

You were almost there with your code, it just needed one more clause in the comprehension to unwind the inner lists.

CodePudding user response:

You can try the itertools module:

result = [[1, 3, 14, 26, 59, 535],[932, 462, 97, 38, 8], [3, 3, 64, 83], [288, 279, 50], [4, 19], [716], [9, 939, 37510]]

from itertools import *

>print(list(chain.from_iterable(result))  # this give a flat list

# if you do want a string:
> ' '.join(str(e) for e in list(chain.from_iterable(result)))
'1 3 14 26 59 535 932 462 97 38 8 3 3 64 83 288 279 50 4 19 716 9 939 37510'
  • Related