2013-11-28 112 views
0

我写了下面的功能:把字符串列表转换成浮动(蟒蛇)的列表

def read_coordinates(filename): 
    invoerfile = open(filename) 
    lines = invoerfile.readlines() 
    for line in lines: 
     seperate_coordinate_rows = line.split("=") 
     for seperate_coordinate_row in seperate_coordinate_rows: 
      row = seperate_coordinate_row.split() 
      print row 

这给了我这些列表:

['5,4', '4,5', '8,7'] 
['6,3', '3,2', '9,6', '4,3'] 
['7,6'] 
['9,8'] 
['5,5', '7,8', '6,5', '6,4'] 

什么我需要添加到这个功能获取带有浮点数的列表作为输出?

+0

你能发表一个输入的例子吗? –

+0

如果您发布了您的输入样本,这里的某个人可能会想出比这更好的解决方案。 –

+0

而不是'['7,6']',它应该是'[7.6]'。这是你想要的吗?还是应该是'[7,6]'? – Sudipta

回答

4

返回一个列表你可以这样使用:

row = map(lambda x: float(x.replace(',','.')), row) 

以上将返回Python 3.x中的一个生成器,它可能会或可能不适合您的需求。如果你需要一个实际的列表,你有两种选择:

# Convert the generator to a list (bad option) 
row = list(row) 

# Or use a list comprehension 
row = [float(x.replace(',','.')) for x in row] 
+0

这将在Python 3.x中返回一个生成器。 –

+3

为什么不在这里使用列表理解? '[float(x.replace(',','。'))for x in row]'。它会比'map'(没有堆栈推送)更快,并且在Python 2和Python 3中都是相同的。 –

+0

修正了它,尽管我不认为OP使用Python 3.x,他也不会在意关于使用listcomp vs maps的性能提升很小。 –

0

把这个放在你的inner for循环中。

row = [float(x.replace(',', '.') for x in row] 
0

地图你的价值观,以float()

row = map(float, seperate_coordinate_row.replace(',', '.').split()) 

map()呼吁在第二个值每个值的第一个参数,有效地返回浮点值的列表。

这里需要.replace()将您的格式转换为float()可识别的格式。

演示:

>>> line = '5,4 4,5 8,7' 
>>> map(float, line.replace(',', '.').split()) 
[5.4, 4.5, 8.7] 

如果您正在使用Python 3,或者只是想反正用一个列表理解,使用:

[float(item.replace(',', '.') for item in seperate_coordinate_row.split()] 

这里.replace()应用于每个拆分项目来代替。

+0

你首先需要用“。”替换“,”。 – jazzpi

+0

我们不应该使用'locales'来处理这些数据吗? – thefourtheye

0

要确保你得到一个列表,最好使用列表理解,因为map不Python3

row = [float(x.replace(",", ".")) for x in seperate_coordinate_row.split()] 
0

替换最后两行

row = [float(item.replace(',', '.')) for item in seperate_coordinate_row.split()] 
print row