Python:从列表中获取多个列表

发布于 2024-10-01 22:49:10 字数 508 浏览 0 评论 0原文

可能的重复:
如何将列表均匀分割Python 中的块大小?

嗨,

我想将一个列表拆分为多个长度为 x 元素的列表,例如:

a = (1, 2, 3, 4, 5)

并获取:

乙 = ( (1,2), (3,4), (5,) )

如果长度设置为 2 或:

乙 = ( (1,2,3), (4,5) )

如果长度等于 3 ...

有没有好的方法来写这个?否则我认为最好的方法是使用迭代器来编写它......

Possible Duplicate:
How do you split a list into evenly sized chunks in Python?

Hi,

I would like to split a list in many list of a length of x elements, like:


a = (1, 2, 3, 4, 5)

and get :


b = (
(1,2),
(3,4),
(5,)
)

if the length is set to 2 or :


b = (
(1,2,3),
(4,5)
)

if the length is equal to 3 ...

Is there a nice way to write this ? Otherwise I think the best way is to write it using an iterator ...

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

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

发布评论

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

评论(3

要走干脆点 2024-10-08 22:49:10

我就是这样做的。迭代,但在列表理解中。注意类型是混合的;这可能是所希望的,也可能不是所希望的。

def sublist(seq, length):
    return [seq[i:i + length] for i in xrange(0, len(seq), length)]

用法:

>>> sublist((1, 2, 3, 4, 5), 1)
[(1,), (2,), (3,), (4,), (5,)]

>>> sublist([1, 2, 3, 4, 5], 2)
[[1, 2], [3, 4], [5]]

>>> sublist('12345', 3)
['123', '45']

>>> sublist([1, 2, 3, 4, 5], 73)
[[1, 2, 3, 4, 5]]

>>> sublist((1, 2, 3, 4, 5), 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in sublist
ValueError: xrange() arg 3 must not be zero

当然,如果您愿意,您也可以轻松地使其生成 tuple - 将列表理解 [...] 替换为 tuple(... )。您还可以将 seq[i:i + length] 替换为 tuple(seq[i:i + length])list(seq[i:i + length]) 使其返回固定类型。

Here's how I'd do it. Iteration, but in a list comprehension. Note the type gets mixed; this may or may not be desired.

def sublist(seq, length):
    return [seq[i:i + length] for i in xrange(0, len(seq), length)]

Usage:

>>> sublist((1, 2, 3, 4, 5), 1)
[(1,), (2,), (3,), (4,), (5,)]

>>> sublist([1, 2, 3, 4, 5], 2)
[[1, 2], [3, 4], [5]]

>>> sublist('12345', 3)
['123', '45']

>>> sublist([1, 2, 3, 4, 5], 73)
[[1, 2, 3, 4, 5]]

>>> sublist((1, 2, 3, 4, 5), 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in sublist
ValueError: xrange() arg 3 must not be zero

Of course, you can easily make it produce a tuple too if you want - replace the list comprehension [...] with tuple(...). You could also replace seq[i:i + length] with tuple(seq[i:i + length]) or list(seq[i:i + length]) to make it return a fixed type.

南街女流氓 2024-10-08 22:49:10

itertools 模块文档。阅读它,学习它,喜欢它。

具体来说,从食谱部分:

import itertools

def grouper(n, iterable, fillvalue=None):
  "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
  args = [iter(iterable)] * n
  return itertools.izip_longest(fillvalue=fillvalue, *args)

给出:

>>> tuple(grouper(3, (1,2,3,4,5)))
((1, 2, 3), (4, 5, None))

这并不完全是你想要的......你不希望其中有None......所以。快速修复:

>>> tuple(tuple(n for n in t if n) for t in grouper(3, (1,2,3,4,5)))
((1, 2, 3), (4, 5))

如果您不喜欢每次都输入列表理解,我们可以将其逻辑移至函数中:

def my_grouper(n, iterable):
  "my_grouper(3, 'ABCDEFG') --> ABC DEF G"
  args = [iter(iterable)] * n
  return tuple(tuple(n for n in t if n)
       for t in itertools.izip_longest(*args))

给出:

>>> tuple(my_grouper(3, (1,2,3,4,5)))
((1, 2, 3), (4, 5))

完成。

The itertools module documentation. Read it, learn it, love it.

Specifically, from the recipes section:

import itertools

def grouper(n, iterable, fillvalue=None):
  "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
  args = [iter(iterable)] * n
  return itertools.izip_longest(fillvalue=fillvalue, *args)

Which gives:

>>> tuple(grouper(3, (1,2,3,4,5)))
((1, 2, 3), (4, 5, None))

which isn't quite what you want...you don't want the None in there...so. a quick fix:

>>> tuple(tuple(n for n in t if n) for t in grouper(3, (1,2,3,4,5)))
((1, 2, 3), (4, 5))

If you don't like typing the list comprehension every time, we can move its logic into the function:

def my_grouper(n, iterable):
  "my_grouper(3, 'ABCDEFG') --> ABC DEF G"
  args = [iter(iterable)] * n
  return tuple(tuple(n for n in t if n)
       for t in itertools.izip_longest(*args))

Which gives:

>>> tuple(my_grouper(3, (1,2,3,4,5)))
((1, 2, 3), (4, 5))

Done.

世态炎凉 2024-10-08 22:49:10

来自 itertools 模块上的 python 文档:

from itertools import izip_longest
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

示例:

>>> tuple(grouper(3, (1, 2, 3, 4, 5, 6, 7)))
((1, 2, 3), (4, 5, 6), (7, None, None))

From the python docs on the itertools module:

from itertools import izip_longest
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

Example:

>>> tuple(grouper(3, (1, 2, 3, 4, 5, 6, 7)))
((1, 2, 3), (4, 5, 6), (7, None, None))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文