简体   繁体   English

从 List 生成相邻元素

[英]Generate adjacent elements from List

I want to generate contiguous sliding window from a list我想从列表中生成连续滑动 window

nums = [1,2,3,4,10]

####O/P 
[[1, 2], [2, 3], [3, 4], [4, 10]]

My code so far -到目前为止我的代码 -

>>> num_list = [1,2,3,4,10]
>>> 
>>> res = []
>>> n = len(num_list)
>>> 
>>> for i in range(n):
...     imm = []
...     for j in range(i,i+1):
...             imm += [num_list[i], num_list[j]]
...     res += [imm]
... 
>>> res
[[1, 1], [2, 2], [3, 3], [4, 4], [10, 10]]

I m beginner in python, the num_list is a just fraction of the actual list, its longer我是 python 的初学者, num_list只是实际列表的一小部分,它更长

What you are trying to achieve is a sliding window您要实现的是滑动 window

You can try the below function, it also reduces your Time Complexity from O(N^2) to O(N)您可以尝试下面的 function,它还可以将您的时间复杂度从 O(N^2) 降低到 O(N)

Other resources其他资源

l = [1,2,3,4,10]

def divide_chunks_contigious(in_arr,chunk):
    n = len(in_arr)
    i = 0
    while i + chunk <= n:
        i += 1
        yield in_arr[i-1:i+chunk-1]

>>> list(divide_chunks_contigious(l,2))
[[1, 2], [2, 3], [3, 4], [4, 10]]

Also the problem with your code can be resolved by initilizing j from i+1 till i+2 , but over long sequences it would be slower您的代码问题也可以通过从i+1i+2初始化j来解决,但是在长序列中它会更慢

for i in range(n-1):
    imm = []
    for j in range(i+1,i+2):
        imm += [num_list[i],num_list[j]]
    res += [imm]

>>> res
[[1, 2], [2, 3], [3, 4], [4, 10]]

You can use zip to create a list of consecutive pairs from the list by passing the original list and a slice of the list offset by 1:您可以使用zip通过传递原始列表和偏移 1 的列表切片从列表中创建连续对的列表:

list(zip(num_list, num_list[1:]))

In your code in second for loop在第二个 for 循环中的代码中

for  j in range(i, i+1):
    print(j)
# j = i

that's why your result is not right you can use this below code这就是为什么你的结果不正确你可以使用下面的代码

n = [1,2,3,4,5]
ans = []
for i in range(len(n)-1):
    ans.append([n[i], n[i+1]])
print(ans)
# ans = [[1,2], [2,3],[3,4],[4,5]]

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

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