将列表元素转换为数字

时间:2017-03-23 05:57:58

标签: python list python-3.x

有一个带有以下三行的csv文件。

8.84,17.22,13.22,3.84
3.99,11.73,19.66,1.27
16.14,18.72,7.43,11.09

我正在编写一个函数,它从文件中读取行并将其附加到空列表中,以便我可以使用该列表来计算均值。

以下是我写的代码:

def my_calc(filename):
    mydata = []
    for line in open(filename).readlines():
         mydata = mydata + line.strip().split(',')
    return mydata

以下是输出:

['"8.84', '17.22', '13.22', '3.84"', '"3.99', '11.73', '19.66', '1.27"', '"16.14', '18.72', '7.43', '11.09"']

列表元素是字符串。如何将这些转换为浮点数?

我尝试map(),但收到错误消息“无法将string转换为float”。

谢谢!

4 个答案:

答案 0 :(得分:2)

试试这个:

a = ['"8.84', '17.22', '13.22', '3.84"', '"3.99', '11.73', '19.66', '1.27"', '"16.14', '18.72', '7.43', '11.09"']
result = map(float, map(lambda x : x.strip('"'), a))

输出:

[8.84, 17.22, 13.22, 3.84, 3.99, 11.73, 19.66, 1.27, 16.14, 18.72, 7.43, 11.09]

如果是python3,请执行以下操作:

result = list(map(float, map(lambda x : x.strip('"'), a)))

答案 1 :(得分:1)

您可以修改您的函数以将项目仅附加到浮动:

<tr>
    <th ng-repeat="(key, value) in mainObj">{{key}}</th>
</tr>

<tr>
    <td >Metal</td>
    <td  ng-repeat="(key, value) in valuesMetal" >{{value}}</td>

</tr>

<tr>
    <td >steel</td>
    <td  ng-repeat="(key, value) in valuessteel" >{{value}}</td>

</tr>

<div>

那应该给出输出:

import re

def my_calc(filename):
    mydata = []
    for line in open(filename).readlines():
        numbers = map(lambda x: float(x), re.sub("['\"]","",line).split(','))
        mydata.append(numbers)
    return mydata

答案 2 :(得分:1)

list = ["8.84,17.22,13.22,3.84", "3.99,11.73,19.66,1.27", "3.99,11.73,19.66,1.27"]
result = []
for el in list:
  strings = el.split(',')
  floats = []
  for el_s in strings:
    floats.append(float(el_s))
  result.append(floats)

print(result, type(result[0][0]))

https://repl.it/G9oO我对lambdas不好,这可以帮到你。

答案 3 :(得分:0)

感谢您发布答案!

这是我的解决方案。我把你所有解决方案的一些部分都拿出来拿出来。

# Workable solution
mylist = []
a = ['"8.84', '17.22', '13.22', '3.84"', '"3.99', '11.73', '19.66', '1.27"', '"16.14', '18.72', '7.43', '11.09"']
for i in range(0,len(a)):
    mylist.append(a[i].lstrip('"').rstrip('"'))
    mylist = [float(x) for x in mylist]
print(mylist)

<强>输出:

[8.84, 17.22, 13.22, 3.84, 3.99, 11.73, 19.66, 1.27, 16.14, 18.72, 7.43, 11.09]