[英]What's the quickest and more efficient way to remove consecutive integers in list?
If I have a list like: infs = [0, 19, 20, 21, 24]
I'd like to remove consecutive values but leave the first only from this group, so here I expect a result: infs = [0, 19, 24]
如果我有一个像这样的列表:
infs = [0, 19, 20, 21, 24]
我想删除连续的值,但只保留该组中的第一个值,因此我希望得到一个结果: infs = [0, 19, 24]
My attempts: 我的尝试:
for k,(i,j) in enumerate(zip(infs, infs[1:])):
print(k,i,j)
if j-i == 1:
del infs[k+1]
It leaves '21' because it was deleted, so this is bad idea to remove it in loop. 因为它已被删除,所以它保留了'21',因此将其循环删除是个坏主意。
You can pair adjacent items in the list by zipping the list with itself but with a padding of its first item, so that you can use a list comprehension that filters out adjacent pairs that differ by just 1: 您可以通过将列表本身与自己的列表进行压缩,但将其第一项填充到列表中,从而对列表中的相邻项进行配对,以便您可以使用列表理解功能过滤出相差仅1的相邻对:
[b for a, b in zip(infs[:1] + infs, infs) if b - a != 1]
This returns: 返回:
[0, 19, 24]
You can use itertools.groupby
over the enumeration of the given list, with a key function that returns the difference between the number and its index: 您可以在给定列表的枚举上使用
itertools.groupby
,并使用键函数返回数字与其索引之间的差:
from itertools import groupby
[next(g)[1] for _, g in groupby(enumerate(infs), lambda t: t[1] - t[0])]
This returns: 返回:
[0, 19, 24]
You simply can do: 您可以做到:
infs=[0, 19, 20, 21, 24]
[v for (i, v) in enumerate(infs) if i==0 or v - infs[i-1] != 1]
[0, 19, 24]
[0、19、24]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.