5

以下示例显示了我在尝试在函数调用中使用字符串函数以进行映射时遇到的错误。我需要帮助了解为什么会发生这种情况。谢谢。

>>> s=["this is a string","python python python","split split split"]
>>> map(split,s)
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    map(split,s)
NameError: name 'split' is not defined

虽然split()是一个内置函数,但它仍然会抛出这个错误?

4

2 回答 2

14

如果您使用它会正常工作str.split()

IE,

s = ["this is a string","python python python","split split split"]
map(str.split, s)

给出:

[['this', 'is', 'a', 'string'],
 ['python', 'python', 'python'],
 ['split', 'split', 'split']]

错误消息指出:NameError: name 'split' is not defined,因此解释器无法识别split,因为splitis not a built-in function。为了使其工作,您必须split与内置str对象关联。

更新:根据@Ivc 的有用评论/建议改进了措辞。

于 2012-06-07T05:00:41.210 回答
2

split不是内置函数,虽然str.split是内置对象的方法。通常,您会将 split 作为str对象的方法调用,这就是直接绑定它的原因。

检查解释器的输出:

>>> str
<type 'str'>
>>> str.split
<method 'split' of 'str' objects>
于 2012-06-07T05:06:10.747 回答