0

我正在研究来自 Google 的 python 练习,但我无法弄清楚为什么我没有得到列表问题的正确答案。我看到了解决方案,他们的做法与我不同,但我认为我这样做的方式也应该有效。

# 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):
  # +++your code here+++
  list = []
  xlist = []
  for word in words:
    list.append(word)
  list.sort()
  for s in list:
    if s.startswith('x'):
      xlist.append(s)
      list.remove(s)
  return xlist+list

电话是:

front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa'])

我得到: ['xaa', 'axx', 'bbb', 'ccc', 'xzz'] 当答案应该是: ['xaa', 'xzz', 'axx', 'b bb', 'ccc ']

我不明白为什么我的解决方案不起作用

谢谢你。

4

2 回答 2

6

您不应该在迭代列表时修改它。for参阅声明文档

  for s in list:
    if s.startswith('x'):
      xlist.append(s)
      list.remove(s)    # this line causes the bug
于 2012-08-21T19:34:01.777 回答
1

试试这个:

def front_x(words):
    lst = []
    xlst = []
    for word in words:
        if word.startswith('x'):
            xlst.append(word)
        else:
            lst.append(word)
    return sorted(xlst)+sorted(lst)


>>> front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa'])
['xaa', 'xzz', 'axx', 'bbb', 'ccc']
于 2012-08-21T19:40:59.307 回答