使用map函数替代for循环
我想要计算一个文件中的行数和单词数。我的输入文件“testfile.txt”有6行和23个单词。为了找出单词的数量,我使用了map()函数,而不是用for循环。当我运行这段代码时,它显示的是对象的内存位置,而不是“23”:
我哪里做错了呢?
def wordcount(l):
global numwords
words = l.split()
numwords += len(words)
f=open('testfile.txt')
lines = f.readlines()
numlines = len(lines)
print ('Number of lines =', numlines)
numwords=0
numwords = map(wordcount, lines)
print ('Number of words =', numwords)
6 个回答
1
你应该避免使用像'numwords'这样的全局变量。你需要在你的wordcount()函数中返回numwords的值。
这个代码是可以正常工作的:
def wordcount(l):
numwords = 0
words = l.split()
numwords += len(words)
return numwords
f = open('testfile.txt')
lines = f.readlines()
numlines = len(lines)
print('Number of lines =', numlines)
numwords = 0
numwords = map(wordcount, lines)
print ('Number of words =', numwords)
我的测试文件testfile.txt包含:
Hello world
my name is
james bond
输出结果 :
('Number of lines =', 3)
('Number of words =', [2, 3, 2])
2
之后:
numwords = map(wordcount, lines)
numwords
是一个和 lines
一样长的列表,里面的内容都是 None
,因为 wordcount
返回的是 None
for line in lines:
words = line.split()
numwords += len(words)
这样写会更好,也更符合 Python 的风格
2
在Python 3中,map
是一个迭代器,类似于itertools.imap
。
class map(object)
| map(func, *iterables) --> map object
|
| Make an iterator that computes the function using arguments from
| each of the iterables. Stops when the shortest iterable is exhausted.
而在Python 2中:
map(...)
map(function, sequence[, sequence, ...]) -> list
它默认返回一个list
(列表)。
所以在你的情况下,你需要这样做:
numwords = list(map(wordcount, lines))
你的代码还有其他问题,不过其他人已经指出得很清楚了。