Skip to content Skip to sidebar Skip to footer

How To Convert Lists Items From String To Int?

I have a list of list of strings as the following list named l: [['1', '2', '3', '4', '5', '6'], ['2', '3', '2', '3', '4']] I want to view the lists as int starting from item 2. T

Solution 1:

Try iterating over your primary list elements.

>>>A = [['1', '2', '3', '4', '5', '6'], ['2', '3', '2', '3', '4']]>>>[list(map(int, x[2:])) for x in A]
[[3, 4, 5, 6], [2, 3, 4]]

Calling list() forces Python 3 to fully evaluate the map - it's not necessary in Python 2.

Solution 2:

You seem to be using Python 3.x. So map produces map object (which is an iterator). You can wrap it in list to see the results:

>>>l = [['1', '2', '3', '4', '5', '6'], ['2', '3', '2', '3', '4']]>>>[list(map(int,l[i][2:])) for i inrange(len(l))]
[[3, 4, 5, 6], [2, 3, 4]]

Second, you iterate index i over range and then use random-access over initial list. In Python you can just iterate over the list without indices: [list(map(int,sub_list[2:])) for sub_list in l]

But I think it's more Pythonic to use list comprehensions:

>>> [[int(i) for i in sub_list[2:]]for sub_list in l]
[[3, 4, 5, 6], [2, 3, 4]]

Post a Comment for "How To Convert Lists Items From String To Int?"