首页 > 解决方案 > 在python中的列表列表上使用定义的函数

问题描述

我有一个定义的功能:

def map(id,txt):
   mapop= []
   words = txt.split()
   for word in words:
     tmp= (word,id,1)
     mapop.append(tmp)
   return mapop 

我尝试使用多种方法将此功能应用于我的列表列表,但它们都不起作用。

  1. 下面给出 AttributeError: 'list' object has no attribute 'split'

    list(map(len,filtered_wordList))
    
  2. 这给出了一个 TypeError: map() missing 1 required positional argument: 'txt'

    [map(item) for item in filtered_wordList] 
    
  3. 这给出了一个 TypeError: map() 接受 2 个位置参数,但给出了 89 个

    mapped=[]
    for line in filtered_wordList:
       temp=map(*line)
    mapped.append(temp)
    

你能否让我知道我哪里出错了。

标签: pythonmapreduce

解决方案


如果您像这样使用函数映射:

text = 'Stack Overflow is great'
map(2, text)

它输出:

[('Stack', 2, 1), ('Overflow', 2, 1), ('is', 2, 1), ('great', 2, 1)]

您的函数接受一个id变量和一个文本(应该是一个字符串)。它像这样在空间上分割文本:

['Stack', 'Overflow', 'is', 'great'] 

并遍历此列表中的每个单词并添加一个元组,其中包含单词、您传递的 id 和 1 到您的mapop列表中,如下所示:

('Stack', 2, 1)

在遍历每个单词后,它返回mapop


推荐阅读