how do I split the values and convert to float in a list if they are all in a single quotation?
我有一份清单,内容如下:
1 2 | a=['0.00244,-0.001908302,-0.001731396,0.002029896,0.000424,0.000291,0.000148 '] |
所以它包含一个包含数字的成员。
我试图寻找不同的方法来提取浮点数格式,如:
如何从列表中的字符串结尾删除''?
从存储在python列表中的每个字符串中删除''
如何删除列表中的"(python)
如何从列表中的字符串结尾删除''?
但它们与我的情况不同的是,我所有的数字都在一个"内"。所以一旦我使用
1 2 | a=[a[0].strip(' ')] |
然后
1 | a[0].split() |
这给了我:
1 | ['0.00244,-0.001908302,-0.001731396,0.002029896,0.000424,0.000291,0.000148'] |
我可以删除,但无法以任何方式提取数字。我想将逗号与数字分开,然后逐个删除,但在我的情况下,拆分似乎不起作用。
正如LGWILLIAMS在评论中提到的。您需要在
考虑到所有这些,您可以执行列表理解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | In [17]: a = ['0.00244,-0.001908302,-0.001731396,0.002029896,0.000424,0.000291,0.000148 '] In [18]: numbers = [float(n) for n in a[0].split(',')] In [19]: numbers Out[19]: [0.00244, -0.001908302, -0.001731396, 0.002029896, 0.000424, 0.000291, 0.000148] |
你也可以使用
1 2 3 4 5 6 7 8 9 | In [22]: list(map(float, a[0].split(','))) Out[22]: [0.00244, -0.001908302, -0.001731396, 0.002029896, 0.000424, 0.000291, 0.000148] |
您可以尝试使用正则表达式从字符串中提取浮点值并转换为浮点值。
1 | list(map(float,re.findall(r'(\-?\d+.\d+)',a[0]))) |
出:
1 2 3 4 5 6 7 | [0.00244, -0.001908302, -0.001731396, 0.002029896, 0.000424, 0.000291, 0.000148] |
一种方法是在逗号上拆分:
1 | '0.00244,-0.001908302,-0.001731396,0.002029896,0.000424,0.000291,0.000148'.split(',') |
会导致:
1 | ['0.00244', '-0.001908302', '-0.001731396', '0.002029896', '0.000424', '0.000291', '0.000148'] |