我正在为来自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’]
我不明白为什么我的解决方案行不通
谢谢。在
试试这个:
迭代列表时不应修改列表。见the ^{} statement documentation 。在
相关问题 更多 >
编程相关推荐