python - 我想分隔这个列表的每个元素,这个列表在python中定义为一个字符串
问题描述
这就是我所拥有的:
undesirable = ['0 0.8770833333333333 0.3712962962962963 0.03567708333333333 0.04537037037037037']
这是我想要的输出:
desirable = [0 , 0.8770833333333333 , 0.3712962962962963 , 0.03567708333333333 ,0.04537037037037037]
如何将不受欢迎的清单转换为理想清单?
解决方案
undesirable = ['0 0.8770833333333333 0.3712962962962963 0.03567708333333333 0.04537037037037037']
desirable = [float(f) for f in undesirable[0].split(" ")]
解释:
undesirable[0] #Gets the "first" item in the list (given that undesirable is a list containing a single string. This returns the string "0 0.877 ... 0.04"
.split(" ") # Splits the string on the space (" ") character, returns a list of the pieces.
float() # Casts the string representations of floats to floats.
这是使用的str.split()
方法。
推荐阅读
- algorithm - Dijkstra 算法的运行时复杂度
- python - 访问具有正确 dtype 的行段
- javascript - 这个用于实现浮动标签输入onfocus的角度ts代码有什么问题?
- mysql - 在 where 子句的 in() 中使用查询语句时获取多行中的一行
- xml - 设置计数器值
- javascript - javascript乘法产生不同的结果
- c# - WPF DataGrid 和 IAsyncEnumerable 项
- php - php中的错误顺序回显
- reactjs - 重新渲染一个组件,它是反应中表格行的一部分
- android - 我无法在 android 中使用 kotlin 在 sqlite 中创建第二个表