在python中删除列表中的相邻元素 [英] Remove adjacent element in a list in python
问题描述
我正在尝试做一个简单的 python 程序来删除列表中的所有相邻元素
I am trying to do a simple python program that removes all the adjacent elements in a list
def main():
a = [1, 5, 2, 3, 3, 1, 2, 3, 5, 6]
c = len(a)
for i in range (0, c-2):
if a[i] == a[i+1]:
del a[i]
c = len(a)
print a
if __name__ == '__main__':
main()
输出为
[1, 5, 2, 3, 3, 2, 3, 5, 6]
没问题!
如果将 a 列表更改为 a = [1, 5, 2, 3, 3, 1, 2, 2, 5, 6]
If change the a list to a = [1, 5, 2, 3, 3, 1, 2, 2, 5, 6]
然后它给出一个错误
索引列表超出范围
**if a[i] == a[i+1]**
它不应该抱怨索引超出范围,因为我每次删除列表中的元素时都会计算 len(a).我在这里缺少什么?
It shouldn't be complaining about the index out of range as I am calculating the len(a) every time it deletes an element in the list. What am I missing here?
推荐答案
for i in range (0, c-2):
这不像其他语言中的 for
循环;它遍历 range
返回的列表(一次).以后更改c
时,不会影响这个循环.
This is not like a for
loop in some other languages; it’s iterating over a list returned (once) by range
. When you change c
later, it does not affect this loop.
你可以改用while
:
c = len(a)
while i < c - 2:
if a[i] == a[i + 1]:
del a[i]
c = len(a)
else:
i += 1
import itertools
def remove_consecutive(l):
return (k for k, v in itertools.groupby(l))
这篇关于在python中删除列表中的相邻元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!