Python - Convert partial sublist's elements in

2020-03-30 07:53发布

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条回答
做个烂人
2楼-- · 2020-03-30 08:02

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])
查看更多
登录 后发表回答