2017-02-11 67 views
0

我是相當新的Python和我在下面的代碼片段使用列表理解:列表理解,如果切片過去列表界爲此

while offset < len(list) 
    s = ['{:04x}'.format(i) for i in list[offset:offset+16]] 
    do stuff with s 
    offset += 16 

的片段遍歷list,並增加了高達 16元素以格式化的方式添加,然後將16添加到偏移值以獲取下一個16,直到看到所有元素。這在我的非簡化代碼中起作用,但是我希望在切片超出列表大小時強加一個佔位符,而不是隻停止向s添加元素。我知道我可以用一個完整的循環來做到這一點,但是爲了保持這個簡潔到一行,我想試着去理解它。我想我需要一個if/else的理解,但似乎無法弄清楚需要什麼條件。

+0

你爲什麼要這麼做?這個過程背後的基本原理是什麼?請記住,「聰明」的代碼通常不如實用的代碼簡潔。 – Soviut

+0

你能舉一個你想在這種情況下執行的動作的例子嗎? – Elisha

+0

代碼的目的是從輸入文件創建一個數據表(我從工作副本中刪除了很多),所以佔位符值將在末尾填入空單元格,並保留所有第16行的長度。通過理解來達到這個目的只是爲了探索如何/如果可以做到。 – yanman1234

回答

1

您可以動態地將切片塊填充到固定大小。例如:

while offset < len(l): 
    s = ['{:04x}'.format(i) for i in l[offset:offset + 16] + [0] * max(0, offset + 16 - len(l))] 
    offset += 16 
    # Do something 

例如具有4固定的大小,此代碼:

WIDTH = 4 
offset = 0 
l = list(range(10)) 
while offset < len(l): 
    s = ['{:04x}'.format(i) for i in 
     l[offset:offset + WIDTH] + [0] * max(0, offset + WIDTH - len(l))] 
    offset += WIDTH 
    print(s) 

收率:

['0000', '0001', '0002', '0003'] 
['0004', '0005', '0006', '0007'] 
['0008', '0009', '0000', '0000'] 
+0

感謝您的幫助,甚至沒有考慮修改列表本身來實現這一點。 – yanman1234

0

串聯您的切片用含有佔位符的列表 - 從而當所述片結束時,將獲取佔位符,並向循環中添加一個具有所需最終大小(第range)的第二個迭代器,以限制第一部分中的已生成項目:

s = ['{:04x}'.format(i) for i, j in in zip(list[offset:offset+16] + ([placeholder] * 16) , range(16)) ] 
0

最簡單的方法是使用某種grouper,爲您提供塊。該itertools -module呈現這樣的功能:

from itertools import zip_longest # or izip_longest in Python2 

def grouper(iterable, n, fillvalue=None): 
    "Collect data into fixed-length chunks or blocks" 
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx" 
    args = [iter(iterable)] * n 
    return zip_longest(*args, fillvalue=fillvalue) 

有了這樣的功能,你可以做這樣的:

lst = list(range(20)) 

for group in grouper(lst, n=8, fillvalue=0): 
    print(['{:04x}'.format(i) for i in group]) 

產生這樣的輸出:

['0000', '0001', '0002', '0003', '0004', '0005', '0006', '0007'] 
['0008', '0009', '000a', '000b', '000c', '000d', '000e', '000f'] 
['0010', '0011', '0012', '0013', '0000', '0000', '0000', '0000']