python - 在python中的列表列表上使用定义的函数
问题描述
我有一个定义的功能:
def map(id,txt):
mapop= []
words = txt.split()
for word in words:
tmp= (word,id,1)
mapop.append(tmp)
return mapop
我尝试使用多种方法将此功能应用于我的列表列表,但它们都不起作用。
下面给出 AttributeError: 'list' object has no attribute 'split'
list(map(len,filtered_wordList))
这给出了一个 TypeError: map() missing 1 required positional argument: 'txt'
[map(item) for item in filtered_wordList]
这给出了一个 TypeError: map() 接受 2 个位置参数,但给出了 89 个
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']
并遍历此列表中的每个单词并添加一个元组,其中包含单词、您传递的 id 和 1 到您的mapop
列表中,如下所示:
('Stack', 2, 1)
在遍历每个单词后,它返回mapop
推荐阅读
- unity3d - 如何将 2d 动画导出为 png 文件?
- android - Flutter:getApplicationSupportDirectory 作为同步方法
- actions-on-google - 我们可以用超过 8000 个关于 dialogflow 和 amazon alexa 的问题来制作常见问题解答技能吗?
- javascript - 如何阻止调整大小栏如此故障?
- ios - XCode 构建系统:弄乱预处理器定义和包含的头文件?
- android - 错误:未知参数--licenses颤振医生--android-licenses
- javascript - 在javascript函数之后,图像边距没有推到浏览器页面的边缘
- javascript - 是否可以在同一个 Ejs 页面上显示集合(mongoDb)和所有集合中的每个元素?
- python - 为什么 GCC 编译的 Python 库在编译器版本之间兼容,而 MSVC 则不兼容?
- javascript - ReactJS Axios 和 Node.js - 数据未定义?