Reputation: 35
I'm new to Python, coming from C; this is my first post, I looked all over for help on how to solve my problem but I cannot find it anywhere unfortunately.
I have a list of lists, and within the lists are strings of numbers(sorting dates):
d = [['2012', '11', '14'], ['2012', '11', '13'], ['2012', '11', '12']]
I am trying to convert these string numbers into integers but i'm not sure how to do it using the way i had used for a normal string list, which was
int_list = [int(x) for x in str_list]
How do i iterate through my list of lists and convert the string numbers into integers so that my list looks like this instead
d = [[2012, 11, 14], [2012, 11, 13], [2012, 11, 12]]
Sorry if this question has been asked before but I could really use some help! Thanks in advance!
Upvotes: 0
Views: 96
Reputation: 11134
You can use map
with list comprehension.
d=[map(int,i) for i in d]
For python 3.x, use:
d=[list(map(int,i)) for i in d]
Upvotes: 1
Reputation: 168626
A nested list comprehension works nicely:
d = [[int(x) for x in sublist] for sublist in d]
Upvotes: 1
Reputation: 5515
just use list comprehension:
>>> d = [['2012', '11', '14'], ['2012', '11', '13'], ['2012', '11', '12']]
>>> i = [[int(x) for x in l] for l in d]
>>> i
[[2012, 11, 14], [2012, 11, 13], [2012, 11, 12]]
i think your problem was that it is a nested list so iterating (int(x)) through d
is trying to convert lists into ints
Upvotes: 1