Python:从列表中获取许多列表 [英] Python : Get many list from a list

查看:155
本文介绍了Python:从列表中获取许多列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
如何将列表平均划分大小的Python块?

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

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

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

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

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

并获取:

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

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

如果长度设置为2或:

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

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

如果长度等于3 ...

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 ...

推荐答案

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

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)

哪个给:

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

这不是您想要的...您不想要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))

哪个给:

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

完成.

这篇关于Python:从列表中获取许多列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆