sort()和list没有属性

时间:2015-10-28 05:31:13

标签: python list attributeerror

我试图进入编程并提出一个简单的问题:

如果我有

def break_words(stuff):
    words = stuff.split(' ')
    return words

def sort_words(words):
    ##Sorts the words."""
    words = break_words(words)
    return sorted(words)

def print_first_word(sentence):
    words = break_words(sentence)
    words = sorted(words)
    return words.pop(0)


sentence = "Tequila Mariachi Sangria"
print break_words(sentence)
print sort_words(sentence)
print print_first_word(sentence)

当我运行它时,我的代码很好,而如果我写

####################Test################

def break_words(stuff):
    words = stuff.split(' ')
    return words

def sort_words(words):
    ##Sorts the words."""
    words = break_words(words)
    return sorted(words)

def print_first_word(sentence):
    words = break_words(sentence)
    words = sort_words(words)
    return words.pop(0)


sentence = "Tequila Mariachi Sangria"
print break_words(sentence)
print sort_words(sentence)
print print_first_word(sentence)

我会得到

AttributeError: "list" object has no attribute "split"

两个函数break_words和sort_words都创建了列表对象,为什么我在第二种情况下得到错误?

2 个答案:

答案 0 :(得分:2)

print_first_word(sentence)来电

words = break_words(sentence)

此处,words现在是一个列表,然后传递给sort_words(words),然后传递给break_words(words),其中调用

words = stuff.split(' ')

其中stuff是一个列表,导致错误。

答案 1 :(得分:0)

我认为第二个源代码应该是:

####################Test################

def break_words(stuff):
    words = stuff.split(' ')
    return words

def sort_words(words):
    ##Sorts the words."""
    words = break_words(words)
    return sorted(words)

def print_first_word(sentence):
    words = sort_words(sentence)
    return words.pop(0)


sentence = "Tequila Mariachi Sangria"
print break_words(sentence)
print sort_words(sentence)
print print_first_word(sentence)

我将words = sort_words(words)更改为words = sort_words(sentence)