Split integers in a list (python)

In python, how would I make a list like [18, 8], into something like [1, 8, 8]?

I already tried to do

list1 = [18, 8] 
list2 = [list1[i : i + 1] for i in range(0, len(times_two_even_even_indexes))]

but it just gives me

list2 = [18], [8]]
+4
source share
5 answers

For the next solution, I would add a refusal: "do not do this at home" ...

lst = [18, 8]
map(int, sum(map(lambda x: list(str(x)), lst), [])) #[1, 8, 8]

Explanation :
str(x)converts each integer to a string, then uses the built-in function listto split the string into a list of characters (each of which is a single digit).

sum(..., [])aligns the list, and the latter map(int, ...)converts all "string digits" to integers.

+1
source

int , / char int:

list1 = [18, 8]

print(list(map(int,"".join(map(str, list1)))))
[1, 8, 8]

comp str int char:

 list1 = [18, 8]

print([int(ch) for i in list1 for ch in str(i)])
[1, 8, 8]
+1

This is the densest form I've tried The inner loop converts a list to a string, then with itertools.chain it smooths the strings to characters and finally converts them back to integers.

import itertools
list2 = [int(y) for y in list(itertools.chain(*[str(x) for x in list1]))]
+1
source

How about this?

intlist = [18, 8]
digitlist = [int(digit) for number in intlist for digit in str(number)]
print digitlist

This converts each number into a list into a string, and then converts each character into a string back to int. Using double-for ( for a in b for x in y) in the understanding of the list, for each character inside, intlistonly one element of the list is displayed.

0
source
#since string is iterable convert to string,
#chain it, and convert back to int

from itertools import  chain

print(list(map(int,chain.from_iterable(map(str,[18, 8])))))

[1, 8, 8]
0
source

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


All Articles