从列表中删除相邻的重复元素
Google Python 类 |列表练习 -
Google Python Class | List Exercise -
给定一个数字列表,返回一个列表,其中所有相邻的 == 元素都被缩减为一个元素,所以 [1, 2, 2, 3] 返回 [1, 2, 3].您可以创建一个新列表或修改传入的列表.
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.
我使用新列表的解决方案是 -
My solution using a new list is -
def remove_adjacent(nums):
a = []
for item in nums:
if len(a):
if a[-1] != item:
a.append(item)
else: a.append(item)
return a
这个问题甚至表明可以通过修改传入的列表来完成.但是,python 文档警告不要在使用 for 循环迭代列表时修改元素.
The question even suggests that it could be done by modifying the passed in list. However, the python documentation warned against modifying elements while iterating a list using the for loop.
我想知道除了迭代列表之外我还能尝试什么来完成这项工作.我不是在寻找解决方案,但也许是一个提示,可以将我带入正确的方向.
I am wondering what else can I try apart from iterating over the list, to get this done. I am not looking for the solution, but maybe a hint that can take me into a right direction.
更新
-使用建议的改进更新了上述代码.
-updated the above code with suggested improvements.
- 使用建议的提示在 while 循环中尝试以下操作 -
-tried the following with a while loop using suggested hints -
def remove_adjacent(nums):
i = 1
while i < len(nums):
if nums[i] == nums[i-1]:
nums.pop(i)
i -= 1
i += 1
return nums
使用生成器迭代列表中的元素,并yield
只有在它发生变化时才产生一个新的.
Use a generator to iterate over the elements of the list, and yield
a new one only when it has changed.
itertools.groupby
确实如此这个.
itertools.groupby
does exactly this.
如果你迭代一个副本,你可以修改传入的列表:
You can modify the passed-in list if you iterate over a copy:
for elt in theList[ : ]:
...