-3

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

  • What is your `result` here? It's not clear here. So it's the `result` - a list of lists? – Daniel Hao May 28 '22 at 16:55
  • @DanielHao result is [1, 3, 14, 26, 59, 535] [932, 462, 97, 38, 8] [3, 3, 64, 83] [288, 279, 50] [4, 19] [716] [9, 939, 37510] –  May 28 '22 at 16:56
  • 1
    So it seems that you want to `flatten` this list (of lists)? Try itertools.chain_from iterable(result) – Daniel Hao May 28 '22 at 16:57
  • Is the input a list of lists? – BrokenBenchmark May 28 '22 at 16:59
  • @DanielHao Thank you! I tried flattening it, however the outside [] still remain...did I do something wrong? –  May 28 '22 at 17:05
  • Does this answer your question? [How do I make a flat list out of a list of lists?](https://stackoverflow.com/questions/952914/how-do-i-make-a-flat-list-out-of-a-list-of-lists) – mkrieger1 May 28 '22 at 17:05
  • 1
    And https://stackoverflow.com/questions/12309976/how-do-i-convert-a-list-into-a-string-with-spaces-in-python – mkrieger1 May 28 '22 at 17:10

2 Answers2

0

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'
Daniel Hao
  • 4,922
  • 3
  • 10
  • 23
0

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.

Mark
  • 90,562
  • 7
  • 108
  • 148