选择所有可能的先前数组/列表元素

时间:2018-07-20 09:40:24

标签: python arrays list

我想在for循环中选择数组/列表的{元素,并将最多存储到列表中的前四个元素+当前元素。因此,随着i的进行,每个循环都会更新此先前元素列表:

i

我的问题是,在运行for循环时,前4个循环不会存储任何a=list(range(0,50)) for i in range(0,len(a)-1): previous_4=a[i-4:i+1] present_element=a[i] print('The present element is {}'.format(present_element)) print('The previous list is {}'.format(previous_4)) 列表,因此不会影响当前元素,因为它位于0索引之下。

previous_4

我想要的是 a 列表中可用的4个先前元素的输出列表:

The present element is 0
The previous list is []
The present element is 1
The previous list is []
The present element is 2
The previous list is []
The present element is 3
The previous list is []
The present element is 4
The previous list is [0, 1, 2, 3, 4]
The present element is 5
The previous list is [1, 2, 3, 4, 5]

有什么办法告诉Python “将这个列表中的任何可用元素都捕获到4个元素之内”

6 个答案:

答案 0 :(得分:3)

问题在于您的切片a[i-4:i+1]是错误的,因为i-4在前四个迭代中为负数。在Python中,负索引是指从列表末尾开始的元素,其中a[-1]是列表a的最后一个元素。因此a[-4:0]返回一个空列表,而a[-4:-1]将返回其最后3个元素。只需更改为

previous_4 = a[max(0,i-4):i+1]

答案 1 :(得分:0)

尝试一下:

a=list(range(0,8))
previous_4=[]
for i in range(0,len(a)-1): 
    previous_4.append(i)
    present_element=a[i]
    print('The present element is {}'.format(present_element))
    print('The previous list is {}'.format(previous_4))
    if(len(previous_4)==5):
        previous_4.pop(0)

答案 2 :(得分:0)

您只需在列表中进行迭代就可以从prevous4列表中追加并弹出

from collections import deque
a=list(range(0,50))
previous_4 = deque([])
for i in range(0,len(a)-1): 
    previous_4.append(a[i])
    if len(previous_4) > 5:
        previous_4.popleft()
    present_element=a[i]

    print('The present element is {}'.format(present_element))
    print('The previous list is {}'.format(previous_4))

答案 3 :(得分:0)

这应该有效:

for i in range(0, len(a)):
     if i < 4: 
         previous_4 = a[ : i+1]
     else:
        previous_4 = a[i-4: i+1]

答案 4 :(得分:0)

@ Kefeng91的答案是一个不错的解决方案(+1),但是大多数答案很差。我想说有更好的方法,就是功能方法!这就是我在适当的生产代码中执行此操作的方式。它高效,可扩展且可重用!

import collections

def get_n_at_a_time(itr, n):
    d = collections.deque(maxlen=n)  # double ended queue of fixed size
    for elem in iterable:
        d.append(elem)
        yield tuple(d)

for sublist in get_n_at_time(range(50), 4):
    print('the current sublist is: {}'.format(list(sublist)))

输出

the current sublist is: [0]
the current sublist is: [0, 1]
the current sublist is: [0, 1, 2]
the current sublist is: [0, 1, 2, 3]
the current sublist is: [1, 2, 3, 4]
the current sublist is: [2, 3, 4, 5]
the current sublist is: [3, 4, 5, 6]
...

答案 5 :(得分:-1)

这有效

a=list(range(0,50))

for i in range(0,len(a)-1): 
    previous_4=a[i-min(4,i):i+1]    #here is the change
    present_element=a[i]

    print('The present element is {}'.format(present_element))
    print('The previous list is {}'.format(previous_4))

说明:-

在您的代码中,i-4中的previous_4=a[i-4:i+1]变为负数,这是不需要的。

即应该是

  

a[i-4:i+1]仅在i>4

     

或简单地a[0:i+1]a[i-i, i+1]

这就是我所做的。