# 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):
previous =''
for i in nums:
if i == previous:
nums.remove(i)
else:
previous = i
return nums
您好,有人可以解释为什么我的代码不起作用。输入[2,2,3,3,3]
输出[2,3,3]而不是[2,3]答案 0 :(得分:3)
从正在迭代的列表中删除项目时会出现问题。迭代的工作原理如下:列表中的每个索引都是从头到尾访问过一次。删除某些内容时,列表内容向左移动:
| 1 | 2 | 3 | 4 | 5 | << your list
| 1 | 2 | | 4 | 5 | << 3 is deleted
| 1 | 2 | 4 | 5 | << the list fills in the gap
但是,迭代器的索引并不知道列表的其余部分已将一个索引更改为左侧,因此它会前进。
通常,这是列表迭代的方式:
| 1 | 2 | 3 | 4 | 5 |
^ < index of iterator
| 1 | 2 | 3 | 4 | 5 |
^ The index advances, all is good.
但是,当你删除术语时,会发生这种情况:
| 1 | 2 | 3 | 4 | 5 |
^ index
| 1 | 2 | 4 | 5 |
^ Oops! The iterator skips over the missing 3, and never gets to it.
你可以通过手动迭代索引来解决这个问题,只有在不的删除时才能推进:
def remove_adjacent(nums):
previous = ''
i = 0;
while i < len(nums):
if nums[i] == previous:
nums.remove(i)
else:
previous = nums[i]
i+=1
return nums
这避免了必须使用[:]制作列表的软拷贝(尽管这是另一种方法)
希望这有帮助!
答案 1 :(得分:1)
获取列表的副本并首先迭代它,否则迭代将失败并出现意外结果
def remove_adjacent(nums):
previous = ''
for i in nums[:]: # using the copy of nums
if i == previous:
nums.remove(i)
else:
previous = i
return nums
>>> remove_adjacent([2,2,3,3,3])
[2, 3]