来自 Google 的 Python 类
#!/usr/bin/python -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
# Additional basic list exercises
# D. Given a list of numbers, return a list where
# all adjacent == elements have been reduced to a single element,
# so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or
# modify the passed in list.
def remove_adjacent(nums):
x = 0
newlist = []
for x in range(0,len(nums),1):
if nums[x] == nums[x+1]:
newlist.append(nums[x])
x = x+2
else:
newlist.append(nums[x])
x = x+1
return nums
它给我一个错误,说列表索引超出范围,但我不确定出了什么问题。我在某处读到,在使用 for 循环进行迭代时无法替换列表中的值,但不知道如何解决。任何意见,将不胜感激。