Python - Convert partial sublist's elements into int

ぐ巨炮叔叔 提交于 2019-12-01 11:40:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!