Skip to main content
 首页 » 编程设计

python之使用 map 函数代替 for 循环

2025年05月04日66lautakyan007

我想查找文件中的行数和单词数。我的输入文件“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) 

请您参考如下方法:

在 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 

它默认返回一个列表。

所以在你的情况下,你需要做:

numwords = list(map(wordcount, lines))

您的代码还存在其他问题,但其他人已经很好地指出了这一点。