在python中的列表列表上使用已定义的函数
我有一个定义的函数:在python中的列表列表上使用已定义的函数,python,mapreduce,Python,Mapreduce,我有一个定义的函数: def map(id,txt): mapop= [] words = txt.split() for word in words: tmp= (word,id,1) mapop.append(tmp) return mapop 我曾尝试使用多种方法将此函数应用于我的列表,但都不起作用 下面给出了AttributeError:“list”对象没有属性“split” list(map(len,filtered_wordList))
def map(id,txt):
mapop= []
words = txt.split()
for word in words:
tmp= (word,id,1)
mapop.append(tmp)
return mapop
我曾尝试使用多种方法将此函数应用于我的列表,但都不起作用
list(map(len,filtered_wordList))
[map(item) for item in filtered_wordList]
mapped=[]
for line in filtered_wordList:
temp=map(*line)
mapped.append(temp)
请告诉我哪里出了问题。如果您这样使用函数图:
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']
('Stack', 2, 1)
并在此列表中的每个单词上循环,并添加一个元组,其中包括单词、您传递的id和1到mapop
列表,如下所示:
['Stack', 'Overflow', 'is', 'great']
('Stack', 2, 1)
在循环遍历每个单词后,它返回
mapop
,正如其他人指出的那样,直接的问题是你在与自己争论:你对函数应该使用什么参数没有一致性——输入文本是一个句子还是一个句子列表。我擅自更改了函数名。这里有一个建议的用法,我认为可以解决你的问题。您可以将几个语句块缩减为一行,但我希望当前版本对您来说更具可读性
filtered_wordlist = [
'Call me Ishmael',
'The boy was odd',
'They could only say it just "happened to happen" and was not very likely to happen again.'
]
def word_id(id,txt):
mapop= []
words = txt.split()
for word in words:
tmp= (word,id,1)
mapop.append(tmp)
return mapop
lexicon = []
for id, sentence in enumerate(filtered_wordlist):
lexicon.append(word_id(id, sentence))
print(lexicon)
输出(具有额外的换行符以便于阅读):
“我尝试在我的列表上应用此功能”-为什么?编写此函数不是为了获取列表。@user2357112我想知道如何将此函数应用于列表中的至少一个。除此之外,
map
是一个,虽然可以像您在这里所做的那样重新定义它,但它通常是一个(非常)糟糕的想法编写此函数是为了获取heckid
应该是什么,以及一个字符串。我不知道你的filtered\u单词列表中有什么,但它不是id
应该是什么和字符串。filtered\u单词列表
似乎是一个列表。因此,您可能最终传递的是一个列表而不是一个字符串。