更新1:代码的最后一行sorted_xlist = sorted(xlist).extend(sorted(words_cp))
应更改为:
sorted_xlist.extend(sorted(xlist))
sorted_xlist.extend(sorted(words_cp))
更新1:更新代码以解决更改words
列表长度的问题。
列表函数的练习来自Google的Python入门课程。我不知道为什么代码在Python 2.7中不起作用。代码的目标在注释部分中解释。
# B. front_x
# Given a list of strings, return a list with the strings
# in sorted order, except group all the strings that begin with 'x' first.
# e.g. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields
# ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
# Hint: this can be done by making 2 lists and sorting each of them
# before combining them.
def front_x(words):
words_cp = []
words_cp.extend(words)
xlist=[]
sorted_xlist=[]
for i in range(0, len(words)):
if words[i][0] == 'x':
xlist.append(words[i])
words_cp.remove(words[i])
print sorted(words_cp) # For debugging
print sorted(xlist) # For debugging
sorted_xlist = sorted(xlist).extend(sorted(words_cp))
return sorted_xlist
更新1:现在错误消息消失了。
front_x
['axx', 'bbb', 'ccc']
['xaa', 'xzz']
X got: None expected: ['xaa', 'xzz', 'axx', 'bbb', 'ccc']
['aaa', 'bbb', 'ccc']
['xaa', 'xcc']
X got: None expected: ['xaa', 'xcc', 'aaa', 'bbb', 'ccc']
['aardvark', 'apple', 'mix']
['xanadu', 'xyz']
X got: None expected: ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
原始列表的拆分工作正常。但合并不起作用。
答案 0 :(得分:3)
当你改变它的长度时,你正在迭代一个序列。
想象一下,如果你开始使用数组
arr = ['a','b','c','d','e']
当你从中删除前两项时,现在你有:
arr = ['c','d','e']
但是你仍在迭代原始数组的长度。最终你到了i> 2,在上面的例子中,它引发了一个IndexError。