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 に答える