迭代时替换列表中的项目

时间:2013-06-14 01:58:20

标签: python python-2.7

来自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循环迭代时无法替换列表中的值,但不知道如何解决这个问题。任何建议将不胜感激。

4 个答案:

答案 0 :(得分:4)

可能是由于nums[x+1]超出了范围。 x仅从0转到len(nums) - 1,这意味着当xlen(nums)-1时,您基本上会将nums[len(nums)]编入索引,这将是一个过去nums的结尾(记住非空列表中的最后一个索引1小于其长度,因为我们从0开始计算索引。

答案 1 :(得分:2)

当x是最后一个元素的索引时,索引x+1将超出范围。此外,您正在创建一个新列表,但是您将返回旧列表。

修改x的值并没有按照您的想法进行,因为它在每次循环迭代时都是重置

以下是另一种实施方式:

def remove_adjacent(nums):
  newlist = []
  for i in range(0, len(nums)):
    if i == len(nums) - 1:      # Avoid out of range error.
      newlist.append(nums[i])
    elif nums[i] == nums[i+1]:  # Skip until the last repeat
      continue
    else:  
      newlist.append(nums[i])
  return newlist    

答案 2 :(得分:2)

你也可以使用zip和list comprehension来做到这一点:

def remove_adjacent(nums):
    return [n[0] for n in zip(nums, nums[1:]) if n[0] != n[1]]

答案 3 :(得分:2)

索引x+1超出列表最后一个元素的范围,其索引为len(nums)-1 - 没有nums[len(nums)]

groupby()模块中使用itertools函数非常简单:

from itertools import groupby

def remove_adjacent(nums):
    return [k for k, _ in groupby(nums)]

print remove_adjacent([1, 2, 2, 2, 3])

输出:

[1, 2, 3]
相关问题