简体   繁体   中英

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]

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.

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:

[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:

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM