根据距离

时间:2017-02-20 21:28:50

标签: python

我有一个数字列表:

numbers = [1,2,3,14,23,45,46,47]

我想创建一个" python-structure" (我不知道究竟要用什么)包含距离小于5的系列

在这种情况下我应该:

1,2,3
45,46,47
你可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

您可以遍历数字,检查差异并相应地将值附加到结果中:

results = [[numbers[0]]]           # initialize the result with the first element of numbers
for x, y in zip(numbers, numbers[1:]):         # use zip to get adjacent values
    if y - x < 5:
        results[-1].append(y)      # if difference is < 5 append result to the last sublist of result
    else:
        results.append([y])        # otherwise start a new sublist
​
results
# [[1, 2, 3], [14], [23], [45, 46, 47]]
相关问题