How to reformat variables in lists in a list to create a single list

A very popular answer, but mine is different from the others. I have a list:

s = [(1, 2, 3),
     (4, 5, 6),
     (7, 8, 9)]

Without other lists, I need to combine my lists inside and make one big list. I need them to be strings, so I do

[map(str, x) for x in s]

But that way I get [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]

Therefore i need ['1', '2', '3', '4', '5', '6', '7', '8', '9']

+4
source share
6 answers

You need to understand the list with planes:

print ([i for x in s for i in map(str, x)])
['1', '2', '3', '4', '5', '6', '7', '8', '9']
+3
source
import itertools
s = [(1, 2, 3),
    (4, 5, 6),
    (7, 8, 9)]
print(list(map(str,itertools.chain(*s))))
+2
source

sum list:

map(str, list(sum(s, ())))
+1

, ,

>>> [str(sii) for si in s for sii in si]
['1', '2', '3', '4', '5', '6', '7', '8', '9']
+1

- reduce, map, .

>>> from functools import reduce

>>> s = [(1, 2, 3), (4, 5, 6),(7, 8, 9)]
>>> list(map(str,reduce(lambda x,y: x+y,s)))
>>> ['1', '2', '3', '4', '5', '6', '7', '8', '9']
+1

itertools.chain :

from itertools import chain

s = [(1, 2, 3),
     (4, 5, 6),
     (7, 8, 9)]

list(map(str, chain.from_iterable(s)))

# ['1', '2', '3', '4', '5', '6', '7', '8', '9']
+1
source

Source: https://habr.com/ru/post/1694163/


All Articles