2012-06-07 117 views
5

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

>>> 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()是一个内置函数,但它仍然会抛出这个错误?

回答

14

它会工作,如果你使用str.split()

即细,

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因为split不是built-in function 。为了实现此目的,您必须将split与内置的str对象关联起来。

更新:措辞改进的基于@ IVC的有帮助的意见/建议。

+0

啊!我明白了,'split()'是一种与对象类型相关的方法(不同于'string','re'等),并且不是一个内置函数,所以我需要指定对象类型来消除歧义。 –

+2

这不是为了消除歧义,而是因为它的字符串方法 -​​ ''blah'.split('a')'等价于'str.split('blah','a')',与'instanceofmyclass .mymethod(arg)'相当于'MyClass.mymethod(instanceofmyclass,arg)' - 该字符串是'str.split'的'self'参数。 – lvc

+11

这是一种丑陋。我宁愿像方法一样调用方法,例如'map(lambda x:x.split(),s)',或者更好一些,就去''[x.split()for s]' –

2

split不是内置函数,但str.split是一个内置对象的方法。一般来说,你可以调用split作为str对象的一种方法,所以这就是它直接绑定的原因。

检查从解释输出:

>>> str 
<type 'str'> 
>>> str.split 
<method 'split' of 'str' objects> 
+0

我不相信这是正确的(str.stplit是一个内置函数)。这里没有列出:http://docs.python.org/library/functions.html,以及与str有关的cleary,所以是一个方法。 – Levon

+0

你是对的。我应该写一个内置的方法。 –

+0

@Jeff我改变它为你。 – jamylak

相关问题