简体   繁体   English

删除列表中连续整数的最快,更有效的方法是什么?

[英]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.

相关问题 用正则表达式循环的更有效方法是什么? - What's a more efficient way of looping with regex? 什么是计算列表最大值的更有效方法? - What is the more efficient way to compute the max of a list? 在 Python 中返回(副本)具有给定 id 的二维列表的一行的最有效(最快)方法是什么? - What is the most efficient (quickest) way to return (a copy of) a row of a two-dimensional list with a given id in Python? 有没有更有效的方法可以根据另一个列表从列表中删除项目? - Is there a more efficient way to remove items from a list based on another list? Python:从列表中剥离后缀字符串的更紧凑/更有效的方法是什么? - Python: what's a more compact/efficient way to strip string of a suffix from list? 计算列表中重复的前导整数数量的最快方法 - Quickest way to count number of repeated leading integers in a list 合并文件的最快方法是什么,拆分数组的最快方法是什么? - what's the quickest way to simple-merge files and what's the quickest way to split an array? 识别列表中连续重复项的最 Pythonic 方法是什么? - What's the most Pythonic way to identify consecutive duplicates in a list? 在列表中生成所有字典组合的更有效方法是什么 - What is the more efficient way to generate all combinations of dicts in a list 将熊猫数据帧转换为位图的更有效方法是什么? - What's a more efficient way to convert pandas dataframe to a bit map?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM