迭代时替换列表中的项目

2024-06-17 13:04:51 发布

您现在位置:Python中文网/ 问答频道 /正文

来自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循环迭代时,不能替换列表中的值,但不知道如何修复它。如有任何建议,将不胜感激。在


Tags: theinhttp列表forreturnusr错误
3条回答

当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    

可能是由于nums[x+1]超出了范围。x只从0到{},这意味着当x是{}时,实际上你将索引到nums[len(nums)],这将是nums结尾的1倍(记住非空列表中的最后一个索引小于其长度{},因为我们从0开始计算索引)。在

索引x+1超出了列表最后一个元素的范围,该元素的索引是len(nums)-1——没有{}。在

只需在^{}模块中使用^{}函数将非常简单:

from itertools import groupby

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

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

输出:

^{pr2}$

相关问题 更多 >