我正在研究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']
我不明白为什么我的解决方案不起作用
谢谢。
答案 0 :(得分:6)
迭代时不应修改列表。请参阅the for
statement documentation。
for s in list:
if s.startswith('x'):
xlist.append(s)
list.remove(s) # this line causes the bug
答案 1 :(得分: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']