2010-10-29 98 views
1

所以我得到了一個字節串,它表示三維立方體。座標是這樣排序的:根據索引將Python列表拆分成幾個列表

[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部分,使一些性能更好。但壓縮絕對不是我強大的一面,二進制文件處理也不是。

+1

你舉的例子是不明確的。它是一個字符串或一個字符串的列表?你爲什麼顯示y127?這是第127個y座標嗎?我以爲只有16個。 – aaronasterling 2010-10-29 10:55:41

+2

這是含糊不清的。請提供顯示實際輸入數據的代碼(不需要解釋的僞代碼)以及該數據的預期結果。 – 2010-10-29 10:57:18

+0

'* 128'部分不需要很長時間,你只需要對同一個迭代器進行128次引用 – 2010-10-29 12:33:09

回答

3
# 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 
+0

b和e有更多的描述性名稱嗎? – l0b0 2010-10-29 12:23:50

+0

'bucket'和'element',如果你願意的話。 – 2010-10-29 12:30:19

0

Itertools可以做到這一點:

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)] 
2

喜歡的東西,這可能是值得一試

L = file["Level"]["Blocks"].value 
col += [L[i::128] for i in range(127)]