代码之家  ›  专栏  ›  技术社区  ›  l0b0

基于索引将Python列表拆分为多个列表

  •  1
  • l0b0  · 技术社区  · 15 年前

    [x0y0z0, x0y1z0, x0y2z0, ..., x0y127z0, x0y0z1, x0y1z1, ..., x15y127z15]
    

    我想把它分成128个列表,每个Y坐标一个。 This code 已经这样做了,但我认为效率低下。有没有办法根据索引的mod(128)来拆分这个列表?

    original code :

    col.extend(izip_longest(*[iter(file["Level"]["Blocks"].value)]*128))
    

    这需要相当长的时间,我认为通过避免 *128 一部分。但压缩绝对不是我的强项,二进制文件处理也不是。

    3 回复  |  直到 15 年前
        1
  •  3
  •   Ignacio Vazquez-Abrams    15 年前
    # l = [x0y0z0, ...]
    def bucketsofun(l, sp=16):
      r = [[] for x in range(sp)]
      for b, e in itertools.izip(itertools.cycle(r), l):
        b.append(e)
      return r
    
        2
  •  2
  •   John La Rooy    15 年前

    像这样的事情也许值得一试

    L = file["Level"]["Blocks"].value
    col += [L[i::128] for i in range(127)]
    
        3
  •  0
  •   Jochen Ritzel    15 年前

    from itertools import izip, izip_longest, chain
    
    def grouper(n, iterable, fillvalue=None):
        "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
        args = [iter(iterable)] * n
        return izip_longest(fillvalue=fillvalue, *args)
    
    # you have something like this
    # [0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
    l = list(chain.from_iterable(range(5) for _ in range(5)))
    
    # you want to put all the 0s, 1s (every 5th element) together
    print list(izip(*grouper(5, l)))
    # [(0, 0, 0, 0, 0), (1, 1, 1, 1, 1), ... , (4, 4, 4, 4, 4)]
    
    推荐文章