python列表方式与google解决方案不同

2024-06-01 00:21:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为来自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

电话是:

^{pr2}$

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

我不明白为什么我的解决方案行不通

谢谢。在


Tags: ofthe答案inapplereturnwith解决方案
2条回答

试试这个:

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']

迭代列表时不应修改列表。见the ^{} statement documentation。在

  for s in list:
    if s.startswith('x'):
      xlist.append(s)
      list.remove(s)    # this line causes the bug

相关问题 更多 >