在 Python 中对列表进行分段

发布于 2024-07-30 02:56:33 字数 444 浏览 5 评论 0原文

我正在寻找一个 python 内置函数(或机制)来将列表分段为所需的段长度(而不改变输入列表)。 这是我已有的代码:

>>> def split_list(list, seg_length):
...     inlist = list[:]
...     outlist = []
...     
...     while inlist:
...         outlist.append(inlist[0:seg_length])
...         inlist[0:seg_length] = []
...     
...     return outlist
... 
>>> alist = range(10)
>>> split_list(alist, 3)
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]

I am looking for an python inbuilt function (or mechanism) to segment a list into required segment lengths (without mutating the input list). Here is the code I already have:

>>> def split_list(list, seg_length):
...     inlist = list[:]
...     outlist = []
...     
...     while inlist:
...         outlist.append(inlist[0:seg_length])
...         inlist[0:seg_length] = []
...     
...     return outlist
... 
>>> alist = range(10)
>>> split_list(alist, 3)
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

梦醒时光 2024-08-06 02:56:33

您可以使用列表理解:

>>> seg_length = 3
>>> a = range(10)
>>> [a[x:x+seg_length] for x in range(0,len(a),seg_length)]
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]

You can use list comprehension:

>>> seg_length = 3
>>> a = range(10)
>>> [a[x:x+seg_length] for x in range(0,len(a),seg_length)]
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
橘亓 2024-08-06 02:56:33

输出不一样,我仍然认为 grouper 函数 很有帮助:

from itertools import izip_longest
def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return izip_longest(*args, fillvalue=fillvalue)

对于 Python2.4和 2.5 没有 izip_longest:

from itertools import izip, chain, repeat
def grouper(iterable, n, padvalue=None):
    return izip(*[chain(iterable, repeat(padvalue, n-1))]*n)

一些演示代码和输出:

alist = range(10)
print list(grouper(alist, 3))

输出:
[(0,1,2),(3,4,5),(6,7,8),(9,无,无)]

not the same output, I still think the grouper function is helpful:

from itertools import izip_longest
def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return izip_longest(*args, fillvalue=fillvalue)

for Python2.4 and 2.5 that does not have izip_longest:

from itertools import izip, chain, repeat
def grouper(iterable, n, padvalue=None):
    return izip(*[chain(iterable, repeat(padvalue, n-1))]*n)

some demo code and output:

alist = range(10)
print list(grouper(alist, 3))

output:
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]

所有深爱都是秘密 2024-08-06 02:56:33

您需要如何使用输出? 如果您只需要迭代它,那么您最好创建一个可迭代的,一个可以产生您的组的迭代:

def split_by(sequence, length):
    iterable = iter(sequence)
    def yield_length():
        for i in xrange(length):
             yield iterable.next()
    while True:
        res = list(yield_length())
        if not res:
            return
        yield res

使用示例:

>>> alist = range(10)
>>> list(split_by(alist, 3))
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]

如果您只循环遍历结果,因为它一次只构造一个子集:

>>> for subset in split_by(alist, 3):
...     print subset
...
[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
[9]

How do you need to use the output? If you only need to iterate over it, you are better off creating an iterable, one that yields your groups:

def split_by(sequence, length):
    iterable = iter(sequence)
    def yield_length():
        for i in xrange(length):
             yield iterable.next()
    while True:
        res = list(yield_length())
        if not res:
            return
        yield res

Usage example:

>>> alist = range(10)
>>> list(split_by(alist, 3))
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]

This uses far less memory than trying to construct the whole list in memory at once, if you are only looping over the result, because it only constructs one subset at a time:

>>> for subset in split_by(alist, 3):
...     print subset
...
[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
[9]
风透绣罗衣 2024-08-06 02:56:33

对 @omergertel 的修改将允许开发人员实际生成段列表:

a = range(9)
seg_length = 3
[list(a[x:x+seg_length]) for x in range(0,len(a),seg_length)]
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]

[a[x:x+seg_length] for x in range(0,len(a),seg_length)]
[range(0, 3), range(3, 6), range(6, 9)]

A modification to @omergertel will allow the developer to actually generate a list of segments:

a = range(9)
seg_length = 3
[list(a[x:x+seg_length]) for x in range(0,len(a),seg_length)]
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]

[a[x:x+seg_length] for x in range(0,len(a),seg_length)]
[range(0, 3), range(3, 6), range(6, 9)]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文