以下示例显示了我在尝试使用函数调用中的字符串函数进行映射时遇到的错误。我需要帮助,为什么发生这种情况。谢谢。为什么我不能在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()
是一个内置函数,但它仍然会抛出这个错误?
啊!我明白了,'split()'是一种与对象类型相关的方法(不同于'string','re'等),并且不是一个内置函数,所以我需要指定对象类型来消除歧义。 –
这不是为了消除歧义,而是因为它的字符串方法 - ''blah'.split('a')'等价于'str.split('blah','a')',与'instanceofmyclass .mymethod(arg)'相当于'MyClass.mymethod(instanceofmyclass,arg)' - 该字符串是'str.split'的'self'参数。 – lvc
这是一种丑陋。我宁愿像方法一样调用方法,例如'map(lambda x:x.split(),s)',或者更好一些,就去''[x.split()for s]' –