来自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循环迭代时,不能替换列表中的值,但不知道如何修复它。如有任何建议,将不胜感激。在
当x是最后一个元素的索引时,索引
x+1
将超出范围。此外,您正在创建一个新列表,但返回旧列表。在修改
x
的值并不是您所想的那样,因为它在每次循环迭代中都是重置。在以下是另一种实现方式:
可能是由于},这意味着当}时,实际上你将索引到},因为我们从
nums[x+1]
超出了范围。x
只从0
到{x
是{nums[len(nums)]
,这将是nums
结尾的1倍(记住非空列表中的最后一个索引小于其长度{0
开始计算索引)。在索引}。在
x+1
超出了列表最后一个元素的范围,该元素的索引是len(nums)-1
——没有{只需在^{} 模块中使用^{} 函数将非常简单:
输出:
^{pr2}$相关问题 更多 >
编程相关推荐