我正在研究来自 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 ']
我不明白为什么我的解决方案不起作用
谢谢你。