【问题标题】:create a nested list from a list where where the difference between consecutive elements is less than a particular number从连续元素之间的差异小于特定数字的列表创建嵌套列表
【发布时间】:2019-11-06 13:08:52
【问题描述】:

我有一个这样的列表,

 l=[1,5,6,9,14,16,17,20,21,29]

现在我想从上面的列表中创建所有可能的列表,条件是连续数字之间的距离小于三。

所以,最终的列表应该是这样的,

l=[[1],[5,6],[9],[14,16,17],[20,21],[29]]

我可以使用 for 循环来做到这一点,但是执行时间很长,有什么办法可以用最少的执行时间来做到这一点。

【问题讨论】:

  • 向我们展示您的尝试minimal reproducible example,我们或许可以帮助您修复错误。什么是“执行时间很长”?什么是“最短执行时间”?使用 for 循环应该是 O(n) - 您需要检查/触摸列表中的每个元素,这样它就不会变得更快。
  • 执行时间有多长?使用 for 循环执行此操作将具有线性复杂度

标签: python list arraylist nested-lists


【解决方案1】:

你能做到这一点的最快时间是 O(n) - 我们需要单独查看每个元素一次。下面的 for 循环就是这样做的。

def consecutive_difference(lst, n):
    rv = []
    consec_list = [l[0]]
    for x in lst[1:]:
        if x - consec_list[-1] >= n:
            rv.append(consec_list)
            consec_list = [x]
        else:
            consec_list.append(x)
    rv.append(consec_list)
    return rv

输出

>>> consecutive_difference(l, 3)
[[1], [5, 6], [9], [14, 16, 17], [20, 21], [29]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 1970-01-01
    • 2013-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多