converting each element from string to int in nested list in python(在PYTHON中将嵌套列表中的每个元素从字符串转换为整数)
本文介绍了在PYTHON中将嵌套列表中的每个元素从字符串转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有带有嵌套列表的python格式的数据,其中的一部分如下所示:
data = [['214', '205', '0', '14', '710', '1813494849', '0'], ['214', '204', '0', '30', '710', '1813494856', '0'], ['214', '204', '0', '34', '710', '1813494863', '0'], ['213', '204', '0', '35', '710', '1813494870', '0'], ['213', '203', '0', '35', '710', '1813494877', '0']]
使用成对方法转换数据时:
1.
new_data_list = [[int(x) for x in list] for list in data]
list=[] for i in range(0,len(data)): list.append([]) for j in range(0,len(data[i])): b=int(data[i][j]) list[i].append(b)
我收到错误消息:
ValueError:基数为10的int()的文本无效:‘’
我的数据列表中没有非数字数据。但标题中可能有一些东西,比如将空标题视为非数字值,因为我已经从CSV创建了一个数据列表。
我想知道一种有效的方法,可以将列表的每个元素转换为int,同时保留数据多列表。
推荐答案
为每个嵌套列表中的每个项目调用int
:
new_list = [[int(x) for x in lst] for lst in nested]
或使用map
:
new_list = [list(map(int, lst)) for lst in nested]
这篇关于在PYTHON中将嵌套列表中的每个元素从字符串转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:在PYTHON中将嵌套列表中的每个元素从字符串转换为整数


基础教程推荐
猜你喜欢
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01