Python 2.7 为什么这个python脚本不能工作?

Python 2.7 为什么这个python脚本不能工作?,python-2.7,Python 2.7,更新1:最后一行代码sorted\u xlist=sortedxlist.extendedsortedwords\u cp应更改为: sorted_xlist.extend(sorted(xlist)) sorted_xlist.extend(sorted(words_cp)) 更新1:更新代码以解决更改单词列表长度的问题 这个列表函数的练习来自Google的Python入门课程。我不知道为什么代码在Python2.7中不起作用。注释部分解释了代码的目标 # B. front_x # Give

更新1:最后一行代码sorted\u xlist=sortedxlist.extendedsortedwords\u cp应更改为:

sorted_xlist.extend(sorted(xlist))
sorted_xlist.extend(sorted(words_cp))
更新1:更新代码以解决更改单词列表长度的问题

这个列表函数的练习来自Google的Python入门课程。我不知道为什么代码在Python2.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']

原始列表的拆分工作正常。但是合并不起作用

在更改序列长度时,您正在对其进行迭代

想象一下,如果从一个数组开始

arr = ['a','b','c','d','e']
当您从中删除前两项时,现在您有:

arr = ['c','d','e']

但您仍在迭代原始数组的长度。在我上面的例子中,最终你会看到i>2,这会产生一个索引器。

你能告诉我们你是如何运行这段代码的吗?作为函数定义,您提供的代码没有问题。您得到的错误似乎表明您没有传递有效的参数。我使用ctrl+b在Sublime中测试代码。谷歌的练习提供了一些测试列表,会告诉你函数的输出是否正确。你是否也希望有人帮你做2-5年的家庭作业?不是关于家庭作业。这是关于学习和理解你的评论是有意义的。错误消息现在不见了。但最终的代码仍然不正确。给我5分钟更新这个问题。啊,我明白了,只要把最后一行代码改为sorted_xlist.extendedsortedxlist sorted_xlist.extendedsortedwords\u cp,现在一切都正常了!谢谢!