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!
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]
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
嵌套列表理解可以很好地工作:
d = [[int(x) for x in sublist] for sublist in d]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.