Python中的map函数

时间:2017-10-21 04:48:22

标签: python python-3.x mapping

文件scores.txt的内容,列出特定游戏中玩家的表现:

80,55,16,26,37,62,49,13,28,56
43,45,47,63,43,65,10,52,30,18
63,71,69,24,54,29,79,83,38,56
46,42,39,14,47,40,72,43,57,47
61,49,65,31,79,62,9,90,65,44
10,28,16,6,61,72,78,55,54,48

以下程序读取文件并将分数存储到列表中

f = open('scores.txt','r')
L = []
for line in f:
    L = L + map(float,str.split(line[:-1],','))
print(L)

但它会导致错误消息。我在课堂上获得了代码,因此对Pyton来说非常新。 我可以修改代码吗?

1 个答案:

答案 0 :(得分:7)

看来你已经改编了在python3.x中使用的python2.x代码。请注意map不返回python3.x中的列表,它返回 生成器 地图对象(不是列表,基本上)你要适当地转换为list

此外,我建议使用list.extend而不是将两者加在一起。为什么?前者在每次执行添加时都会创建一个新的列表对象,并且在时间和空间方面都是浪费。

numbers = []
for line in f:
    numbers.extend(list(map(float, line.rstrip().split(','))))

print(numbers)

另一种方法是:

for line in f:
    numbers.extend([float(x) for x in line.rstrip().split(',')]) 

哪个更具可读性。您还可以选择使用嵌套列表解析来摆脱外部for循环。

numbers = [float(x) for line in f for x in line.rstrip().split(',')]

另外,忘了提这个(感谢chris in the comments),但你真的应该使用上下文管理器来处理文件I / O.

with open('scores.txt', 'r') as f:
    ...

它更干净,因为它会在您完成文件后自动关闭文件。

在看到您的ValueError消息后,很明显您的数据存在问题(无效字符等)。让我们尝试一些更积极的东西。

numbers = []
with open('scores.txt', 'r') as f:
    for line in f:
        for x in line.strip().split(','):
            try:
                numbers.append(float(x.strip()))
            except ValueError:
                pass

如果即使这样也行不通,那么正则表达式更具攻击性的东西可能会这样做:

import re

numbers = []
with open('scores.txt', 'r') as f:
    for line in f:
        line = re.sub('[^\d\s,.+-]', '', line)
        ... # the rest remains the same
相关问题