列表列表,将所有字符串转换为 int,Python 3
- 作者: 丶妖冶叔叔
- 来源: 51数据库
- 2022-12-23
问题描述
我正在尝试将大列表中小列表的所有元素转换为整数,所以它应该如下所示:
I am trying to convert all elements of the small lists in the big list to integers, so it should look like this:
current list:
list = [['1','2','3'],['8','6','8'],['2','9','3'],['2','5','7'],['5','4','1'],['0','8','7']]
for e in list:
for i in e:
i = int(i)
new list:
list = [[1,2,3],[8,6,8],[2,9,3],[2,5,7],[5,4,1],[0,8,7]]
谁能告诉我为什么这不起作用并向我展示一种有效的方法?谢谢!
Could anyone tell me why doesn't this work and show me a method that does work? Thanks!
推荐答案
你可以使用嵌套列表推导:
You can use a nested list comprehension:
converted = [[int(num) for num in sub] for sub in lst]
我也将list重命名为lst,因为list是列表类型的名称,不推荐用于变量名.
I also renamed list to lst, because list is the name of the list type and not recommended to use for variable names.
推荐阅读
热点文章
Discord.py(重写)on_member_update 无法正常工作
0
Discord.py 在 vc 中获取用户分钟数
0
discord.py 重写 |为我的命令出错
0
Discord.py rewrite 如何 DM 命令?
0
播放音频时,最后一部分被切断.如何解决这个问题?(discord.py)
0
在消息删除消息 Discord.py
0
如何使 discord.py 机器人私人/直接消息不是作者的人?
0
(Discord.py) 如何获取整个嵌入内容?
0
Discord bot 尽管获得了许可,但不能提及所有人
0
Discord.py discord.NotFound 异常
0
