Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten a list of lists containing single strings to a list of ints [duplicate]

Tags:

python

i have list with lists of strings looks like

allyears
#[['1916'], ['1919'], ['1922'], ['1912'], ['1924'], ['1920']]

i need to have output like this:

#[1916, 1919, 1922, 1912, 1924, 1920]

have been try this:

for i in range(0, len(allyears)): 
    allyears[i] = int(allyears[i]) 

but i have error

>>> TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
like image 854
germanjke Avatar asked Apr 03 '20 08:04

germanjke


2 Answers

You're very close, you just need to take the first (and only) element of allyears[i] before doing the int conversion:

for i in range(0, len(allyears)): 
    allyears[i] = int(allyears[i][0]) 

Alternatively, you could do this in one line using a list comprehension:

allyears = [int(l[0]) for l in allyears]
like image 197
dspencer Avatar answered Sep 25 '22 07:09

dspencer


You can simply do this:

allyears = [int(i[0]) for i in allyears]

Because all the elements in your allyears is a list which has ony one element, so I get it by i[0]

The error is because ypu can't convert a list to an int

like image 29
Binh Avatar answered Sep 23 '22 07:09

Binh