问题
Suppose you have a list like:
[["a", "1", "2", "3"], ["b", "4", "5", "6"], ["c", "7", "8", "9"]]
And I want to convert the elements from index 1 to 2 of every sublist into integers as you can see they are themselves strings. Is it possible? If it is, then what is the shortest way to do it? What have I done uptil now is this:
lists = [["a", "1", "2", "3"], ["b", "4", "5", "6"], ["c", "7", "8", "9"]]
for l in lists:
l[1:4] = [int(x) for x in l[1:4]]
print(lists)
回答1:
If you want to convert the lists inplace, your code is good enough.
BTW, the list comprehension can be replaced with map
:
l[1:4] = map(int, l[1:4])
来源:https://stackoverflow.com/questions/22272359/python-convert-partial-sublists-elements-into-int