简体   繁体   English

如何根据Python中连续元素的距离拆分数字列表?

[英]How to split a list of numbers based on the distance of consecutive elements in Python?

Given a list of numbers, how can I split it whenever the distance of two adjacent elements is larger than n ? 给定一个数字列表,每当两个相邻元素的距离大于n时,如何拆分它?

Input: 输入:

n = 3   
l = [1, 2, 5, 3, -2, -1, 4, 5, 2, 4, 8]

Output: 输出:

[[1, 2, 5, 3], [-2, -1], [4, 5, 2, 4], [8]]

You can do it using zip: 您可以使用zip来实现:

# initialization
>>> lst = [1, 2, 5, 3, -2, -1, 4, 5, 2, 4, 8]
>>> n = 3

Find splitting locations using zip: 使用zip查找拆分位置:

>>> indices = [i + 1 for (x, y, i) in zip(lst, lst[1:], range(len(lst))) if n < abs(x - y)]

Slice subslists using previous result: 使用先前的结果切片子列表:

# pad start index list with 0 and end index list with length of original list
>>> result = [lst[start:end] for start, end in zip([0] + indices, indices + [len(lst)])]
>>> result
[[1, 2, 5, 3], [-2, -1], [4, 5, 2, 4], [8]]

Code

from boltons import iterutils

def grouponpairs(l, f):
    groups = []
    g = []
    pairs = iterutils.pairwise(l + [None])
    for a, b in pairs:
        g.append(a)
        if b is None:
            continue
        if not f(a, b):
            groups.append(g)
            g = []
    groups.append(g)
    return groups

Test 测试

grouponpairs([1, 2, 5, 3, -2, -1, 4, 5, 2, 4, 8], lambda a, b: abs(a - b) <= 3)
# [[1, 2, 5, 3], [-2, -1], [4, 5, 2, 4], [8]]

Here's a more primitive piece of code that achieves what you want to do, even though it is not efficient (see Reut Sharabani's answer for a more efficient solution.) 这是一段更原始的代码,即使它效率不高,也可以实现您想要执行的操作(有关更有效的解决方案,请参阅Reut Sharabani的回答)。

# Input list
l = [1, 6, 5, 3, 5, 0, -3, -5, 2]
# Difference to split list with
n = 3

output = []
t = []
for i in range(1, len(l)):
    t.append(l[i])
    if abs(l[i] - l[i - 1]) < n:
        None
    else:
        output.append(t)
        t = []
return output
n = 3
a = [1, 2, 5, 3, -2, -1, 4, 5, 2, 4, 8]

b = [abs(i - j) > n for i, j in zip(a[:-1], a[1:])]
m = [i + 1 for i, j in enumerate(b) if j is True]
m = [0] + m + [len(a)]
result = [a[i: j] for i, j in zip(m[:-1], m[1:])]

print(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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