首页 > 解决方案 > 我想分隔这个列表的每个元素,这个列表在python中定义为一个字符串

问题描述

这就是我所拥有的:

undesirable = ['0   0.8770833333333333   0.3712962962962963   0.03567708333333333   0.04537037037037037']

这是我想要的输出:

desirable = [0 , 0.8770833333333333 ,  0.3712962962962963 , 0.03567708333333333 ,0.04537037037037037]

如何将不受欢迎的清单转换为理想清单?

标签: python

解决方案


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()方法。


推荐阅读