![](/img/trans.png)
[英]How to input the results of the split from the list of sensor data (.txt) into a variable
[英]Data from txt input to list - Python
我在文本文件中有数据:
2,58 1,23 0,14
6,58 4,2 1,3
我想从我的文本文件中以这种格式写入列表中的这些数据:
[[2, 58, 1, 23, 0, 14]
[6, 58, 4, 2, 1, 3]]
我试过这个:
folder = open('text.txt', encoding = 'utf-8')
data = [numbers.strip().replace(',',' ').split(' ') for numbers in folder]
folder.close
print(data)
但我收到这样的结果: [['2', '58', '1', '23', '0', '14']['6', '58', '4', '2', '1', '3']]
如果我试图将int()
设置为列表中许多地方的数字,我会收到此错误: int() 参数必须是字符串、类似字节的对象或数字,而不是list
所以我只需要将这个列表中的所有字符串从str
更改为int
,你能帮我吗?
尝试使用map()
函数,它需要两个参数,其中一个是函数、条件等,第二个是可迭代对象,如列表、集合等,因此在您的问题中将类似于map (int ,yourlist)
并在将其转换为像list(map (int ,yourlist))
这样的list(map (int ,yourlist))
请参阅此问题以了解为什么要投射它
folder = open('text.txt', encoding = 'utf-8')
data = [list(map(int, numbers.strip().replace(',',' ').split(' '))) for numbers in folder]
folder.close()
print(data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.