user1870662
user1870662

Reputation: 13

How to convert a list of string to a list of int

I have this list in a list

a = [['1','2','3','4'],['1','2','3','4'],['1','2','3','4']]

but i need it to be ints , im not sure where to use int() to change str to int

a = [[1,2,3,4],[1,2,3,4],[1,2,3,4]]

Upvotes: 0

Views: 235

Answers (4)

arshajii
arshajii

Reputation: 129497

Here's an idea:

>>> a = [['1','2','3','4'],['1','2','3','4'],['1','2','3','4']]
>>> map(lambda l: map(int, l), a)
[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]

Upvotes: 0

NPE
NPE

Reputation: 500257

In [51]: a = [['1','2','3','4'],['1','2','3','4'],['1','2','3','4']]

In [52]: [map(int, l) for l in a]
Out[52]: [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]

Upvotes: 1

Yudhishthir Singh
Yudhishthir Singh

Reputation: 238

You can use a nested list comprehension like so:

a = [['1','2','3','4'],['1','2','3','4'],['1','2','3','4']]
b = [ [int(j) for j in i] for i in a]

Upvotes: 3

Lev Levitsky
Lev Levitsky

Reputation: 65791

An example using nested list comprehension:

In [1]: a = [['1','2','3','4'],['1','2','3','4'],['1','2','3','4']]

In [2]: [[int(s) for s in l] for l in a]
Out[2]: [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]

Upvotes: 0

Related Questions