如何在python族元素由n个元素? [英] How to group elements in python by n elements?

查看:150
本文介绍了如何在python族元素由n个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python\">How你分割成列表在Python均匀大小的块?


我想获得大小为n个元素的组从列表L:

例如:

  [1,2,3,4,5,6,7,8,9]  - &GT; [[1,2,3],[4,5,6],[7,8,9],其中n为3


解决方案

您可以使用来自食谱石斑鱼和itertools文档页面:

 高清石斑鱼(N,迭代,fillvalue =无):
    石斑鱼(3,'ABCDEFG','X') - GT; ABC DEF GXX
    ARGS = [国际热核实验堆(迭代器)] * N
    返回izip_longest(fillvalue = fillvalue,*参数)

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

I'd like to get groups of size n elements from a list l:

ie:

[1,2,3,4,5,6,7,8,9] -> [[1,2,3], [4,5,6],[7,8,9]] where n is 3

解决方案

You can use grouper from the recipes on the itertools documentation page:

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

这篇关于如何在python族元素由n个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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