繁体   English   中英

在python中按列表顺序选择n个项目

[英]Select n items by sequence of a list repeatedly in python

说我有一长串清单:

>>> import string
>>> my_list = list(string.ascii_lowercase)
>>> my_list
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] 

我想循环遍历此列表并重复按顺序选择n个项目。 例如,如果我想选择5个项目,那么应该是这样的:

step 1: ['a', 'b', 'c', 'd', 'e']
step 2: ['f', 'g', 'h', 'i', 'j']
step 3: ['k', 'l', 'm', 'n', 'o']
step 4: ['p', 'q', 'r', 's', 't']
step 5: ['u', 'v', 'w', 'x', 'y']
step 6: ['z', 'a', 'b', 'c', 'd']
step 7: ['e', 'f', 'g', 'h', 'i']
......

所以关键是: 我想确保当我到达列表的最后一项时,第一项可以附加到最后一项,循环只是继续。


为了将第一个项目附加到最后一项,我尝试过这样的事情:

def loop_slicing(lst_, i):
    """ Slice iterable repeatedly """
    if i[0] > i[1]:
        return [n for n in lst_[i[0]:]+lst_[:i[1]]]
    else:
        return lst_[i[0]:i[1]]

当我调用此函数时,我可以这样做:

>>> loop_slicing(my_list, (0, 5))
['a', 'b', 'c', 'd', 'e']
>>> loop_slicing(my_list, (25, 4))
['z', 'a', 'b', 'c', 'd']

我可以制作一个生成器,它可以生成range(0, 26) my_list range(0, 26) 5个连续数字,以循环遍历my_list ,每次获得5个项目。

我不知道这是不是最好的方法。 那么有没有更有效的方法来做这些事情?

使用itertools模块,您可以通过无限生成器循环和切片字符串:

from itertools import cycle, islice
from string import ascii_lowercase

def gen(x, n):
    c = cycle(x)
    while True:
        yield list(islice(c, n))

G = gen(ascii_lowercase, 5)

print(next(G))  # ['a', 'b', 'c', 'd', 'e']
print(next(G))  # ['f', 'g', 'h', 'i', 'j']
...
print(next(G))  # ['u', 'v', 'w', 'x', 'y']
print(next(G))  # ['z', 'a', 'b', 'c', 'd']

使用列表理解的解释性更简单的解决方案:

def batch_list(ns, batch_size):
    return [ns[i:i+batch_size] for i in range(0, len(ns), batch_size)]

>>> batch_list('abcdefghijk', 3) 
['abc', 'def', 'ghi', 'jk']

这是一个简单的结构,当我想要批量执行一些任务列表时,我发现自己经常写。

编辑:刚刚意识到OP要求施工循环到开始,以便在需要时完成最后一批。 这不会那样做,并会截断最后一批。

谢谢你问,

我花了一些时间来了解您的算法的目标,但如果您想循环并保存所有子列表,我认为这应该工作:

def slicing_items(slc_len = 5, lst, iterate_num = 25):
# slc_len correspond to the number of slices, lst is the list of sequences
n = len(lst)
k = 1
p = k * slc_len
slicing_list = []
while k < iterate_num:
    current_slice = []
    if p >= n:    
        for i in range (1, p//n):
            current_slice += lst                  #How many times we passed the length of the list
        p = p % n                                 #How many items remaining ?
        current_slice += lst[-(slc_len-p):] 
        current_slice += lst[:p]

    else:
        current_slice = lst[p-slc_len:p]
    k += 1
    p += slc_len
    slicing_list.append(current_slice)

return slicing_list

输出:

slicing_items(5,my_list,10)

>>> [['a', 'b', 'c', 'd', 'e'],
['f', 'g', 'h', 'i', 'j'],
['k', 'l', 'm', 'n', 'o'],
['p', 'q', 'r', 's', 't'],
['u', 'v', 'w', 'x', 'y'],
['z', 'a', 'b', 'c', 'd'],
['e', 'f', 'g', 'h', 'i'],
['j', 'k', 'l', 'm', 'n'],
['o', 'p', 'q', 'r', 's']]

但是,如果你只想要你的iterate_num的最后一个切片,那么你的函数应该完全适合(也许你应该使用切片而不是重写第一个布尔语句中的列表以获得快速性)

使用发电机和切片:

from string import ascii_lowercase

def gen(x, n):
    start, stop = 0, n
    while True:
        if start < stop:
            yield list(x[start:stop])
        else:
            yield ((list(x[start:])) + (list(x[:stop])))
        start = stop
        stop = (stop + n) % len(x)


G = gen(ascii_lowercase, 5)

print(next(G))  # ['a', 'b', 'c', 'd', 'e']
print(next(G))  # ['f', 'g', 'h', 'i', 'j']
print(next(G))
print(next(G))
print(next(G))  # ['u', 'v', 'w', 'x', 'y']
print(next(G))  # ['z', 'a', 'b', 'c', 'd']
print(next(G))

输出:

['a', 'b', 'c', 'd', 'e']
['f', 'g', 'h', 'i', 'j']
['k', 'l', 'm', 'n', 'o']
['p', 'q', 'r', 's', 't']
['u', 'v', 'w', 'x', 'y']
['z', 'a', 'b', 'c', 'd']
['e', 'f', 'g', 'h', 'i']

这是一个非常有趣的问题,如果你想“只是”解决问题去迭代循环方法,它已经内置了函数,但如果你想享受算法构建的乐趣,那就去自己的解决方案吧东西:

在这里我尝试使用递归方法,正如你所说它会继续下去所以你必须通过设置你的最大限制来处理递归:

import math
import sys
sys.setrecursionlimit(500)

data=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
try:
    def recursive_approch(m, x, n, hold=0, value=0, left=0):
        print(hold)

        max_time = len(m) / n
        max_t = int(math.modf(max_time)[1])
        left = len(m) % n

        if value == max_t:

            if len(x) == left:
                x = x + m[:-len(x)]
                value = 0
                left = 0
        else:

            hold = x[:n]
            value = value + 1
            return recursive_approch(m, x[n:], n, hold=hold, value=value, left=left)
        return recursive_approch(m, x, n, hold=hold, value=value, left=left)


    print(recursive_approch(data, data, 6))
except RecursionError:
    print('maximum recursion')

你必须传递切片的数字,所以如果你想切片6-6然后:print(recursive_approch(data,data,6))输出:

['a', 'b', 'c', 'd', 'e', 'f']
['g', 'h', 'i', 'j', 'k', 'l']
['m', 'n', 'o', 'p', 'q', 'r']
['s', 't', 'u', 'v', 'w', 'x']
['s', 't', 'u', 'v', 'w', 'x']
['y', 'z', 'a', 'b', 'c', 'd']
['e', 'f', 'g', 'h', 'i', 'j']
['k', 'l', 'm', 'n', 'o', 'p']
['q', 'r', 's', 't', 'u', 'v']
['q', 'r', 's', 't', 'u', 'v']
['w', 'x', 'a', 'b', 'c', 'd']
['e', 'f', 'g', 'h', 'i', 'j']
['k', 'l', 'm', 'n', 'o', 'p']
['q', 'r', 's', 't', 'u', 'v']
['q', 'r', 's', 't', 'u', 'v']
['w', 'x', 'a', 'b', 'c', 'd']
['e', 'f', 'g', 'h', 'i', 'j']
...................

如果你想要3-3那么:

['a', 'b', 'c']
['d', 'e', 'f']
['g', 'h', 'i']
['j', 'k', 'l']
['m', 'n', 'o']
['p', 'q', 'r']
['s', 't', 'u']
['v', 'w', 'x']
['v', 'w', 'x']
['y', 'z', 'a']
['b', 'c', 'd']
['e', 'f', 'g']
['h', 'i', 'j']
['k', 'l', 'm']
['n', 'o', 'p']
['q', 'r', 's']
['t', 'u', 'v']
['t', 'u', 'v']
['w', 'x', 'a']
['b', 'c', 'd']
['e', 'f', 'g']
['h', 'i', 'j']
['k', 'l', 'm']
['n', 'o', 'p']
['q', 'r', 's']
['t', 'u', 'v']
['t', 'u', 'v']
['w', 'x', 'a']
['b', 'c', 'd']
['e', 'f', 'g']
['h', 'i', 'j']
['k', 'l', 'm']
['n', 'o', 'p']
['q', 'r', 's']
['t', 'u', 'v']
['t', 'u', 'v']
['w', 'x', 'a']
['b', 'c', 'd']
['e', 'f', 'g']
['h', 'i', 'j']
['k', 'l', 'm']
['n', 'o', 'p']
['q', 'r', 's']
['t', 'u', 'v']
['t', 'u', 'v']
['w', 'x', 'a']
['b', 'c', 'd']
.......

如果你通过12:

0
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l']
['m', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x']
['m', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x']
['y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
['k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v']
['k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v']
['w', 'x', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
['k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v']
['k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v']
['w', 'x', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
['k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v']
['k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v']
['w', 'x', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
['k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v']
['k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v']
['w', 'x', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
['k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v']
['k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v']
....

暂无
暂无

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

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