Python - 将部分子列表的元素转换为int [英] Python - Convert partial sublist's elements into int

查看:629
本文介绍了Python - 将部分子列表的元素转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有以下列表:

[["a", "1", "2", "3"], ["b", "4", "5", "6"], ["c", "7", "8", "9"]]

我想将每个子列表的索引1到2的元素转换为整数,因为您可以看到它们本身就是字符串。可能吗?如果是,那么最简单的方法是什么?我现在做了什么:

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)


推荐答案

如果你想在里面转换列表,你的代码就足够了。

If you want to convert the lists inplace, your code is good enough.

BTW,列表理解可以替换为 map

BTW, the list comprehension can be replaced with map:

l[1:4] = map(int, l[1:4])

这篇关于Python - 将部分子列表的元素转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆