如何在给定的数字集中使用逗号而不是空格

时间:2015-12-08 02:26:15

标签: python list

我有一组数字说

s = "39401.99865    7292.4753   8541.03675  6098.54185  106352.218  7300.4485   5699.983    5538.44755  5934.8514   7477.62475  5956.7409   9170.98 9481.5082   6063.4508   9380.92255" 

我想创建一个这样的数字列表,如

my_list = [ 39401.99865, 7292.4753  8541.03675, 6098.54185 , 106352.218 ,   7300.4485 ,5699.983 ,5538.44755 5934.8514, 7477.62475,  5956.7409,  9170.98,    9481.5082,  6063.4508   9380.92255] 

我怎样才能做到这一点?我尝试使用正则表达式,但它将我的数据转换为字符串。

s = '98 9 19'
s = re.sub(r'(?<=\d)\s+(?=\d)', ',', s)

print s

1 个答案:

答案 0 :(得分:0)

>>> s = "39401.99865    7292.4753   8541.03675  6098.54185  106352.218  7300.4485   5699.983    5538.44755  5934.8514   7477.62475  5956.7409   9170.98 9481.5082   6063.4508   9380.92255" 
>>> [float(item) for item in s.split()]
[39401.99865, 7292.4753, 8541.03675, 6098.54185, 106352.218, 7300.4485, 5699.983, 5538.44755, 5934.8514, 7477.62475, 5956.7409, 9170.98, 9481.5082, 6063.4508, 9380.92255]

或者您可以使用map

>>> map(float, s.split())
[39401.99865, 7292.4753, 8541.03675, 6098.54185, 106352.218, 7300.4485, 5699.983, 5538.44755, 5934.8514, 7477.62475, 5956.7409, 9170.98, 9481.5082, 6063.4508, 9380.92255]