均分list

题面儿

OnMyWay <[email protected]>
reply-to        [email protected]
to      [email protected]
date    Fri, Mar 6, 2009 at 21:03
subject [CPyUG:80732] 如何等分一个list?

   aa = range(100)
   bb = func(aa)
   print bb
   [[0:9],[10:19],[20:29],.....]

推导式

萧萧 <[email protected]>

[a[m:m+10] for m in range(100) if m%10==0] 

bob ning <[email protected]>

[ range(i, i+10) for i in range(0, 100, 10) ]

zip()

Li Feng <[email protected]>

zip(*(iter(L),)*10)

http://docs.python.org/library/functions.html#zip

点评

shell909090 <[email protected]>我多嘴说一下为啥吧,刚刚看了半天。

  • 首先,是一个基础语法,iter(L),某个列表的枚举函数。
    • 按照zip的语法,其实it=iter(L);zip(it,it..重复10次..),就可以达到目标。
      • 原因是zip会从头一个函数获得头一组的第一个对象,第二个函数获得头一组的第二个对象。而这正好是第二个元素。
  • 那么zip(*(iter(L),)*10)呢?
    • 首先,我加个括号zip(*((iter(L),)*10))。
    • 大家可以看到,结果不变。
    • ((iter(L),)*10)是一个语法糖,将某个tuply的内容重复10次。
    • 而后,通过zip(*arg)的语法,这10次的iter(L)就被作为参数传入了zip。的却非常不直观。

  • yield

    Qiangning Hong <[email protected]>

    web.py 里的代码:

       1 def group(seq, size):
       2    """
       3    Returns an iterator over a series of lists of length size from iterable.
       4 
       5        >>> list(group([1,2,3,4], 2))
       6        [[1, 2], [3, 4]]
       7    """
       8    if not hasattr(seq, 'next'):
       9        seq = iter(seq)
      10    while True:
      11        yield [seq.next() for i in xrange(size)]
    


    反馈

    创建 by -- ZoomQuiet [2009-03-06 14:54:38]

    MiscItems/2009-03-06 (last edited 2009-12-25 07:09:53 by localhost)