2014-02-20 68 views
3

是否可以拆分列表中的項目並隨時生成新列表? 基本上我得到USHORT的列表,並希望產生ubytes列表:拆分列表中的每個項目

input = [1036, 1055, 26, 29787, 9, 4206, 41, 7, 1036, 8302, 130, 4, 268, 4206] 
out = [4, 12, 4, 31, 0, 26, 116, 91, 0, 9, 16, 110, 0, 41, 0, 7, 4, 12, 32, 110, 0, 130, 0, 4, 1, 12, 16, 110] 

,我可以很輕鬆地生成一個元組列表,但我怎麼能刪除的元組,並把它們合併到一個大名單?

out_temp = [(x>>8, x&0xFF) for x in input] 
+1

你爲什麼不使用lambda funtion? – Trimax

回答

6

您可以使用列表理解是這樣的:

>>> in_ = [1036, 1055, 26, 29787, 9, 4206, 41, 7, 1036, 8302, 130, 4, 268, 4206] 
>>> [y for x in in_ for y in (x >> 8, x & 0xff)] 
[4, 12, 4, 31, 0, 26, 116, 91, 0, 9, 16, 110, 0, 41, 0, 7, 4, 12, 32, 110, 0, 130, 0, 4, 1, 12, 16, 110] 

或使用itertools.chain.from_iterable

>>> import itertools 
>>> list(itertools.chain.from_iterable((x >> 8, x & 0xff) for x in in_)) 
[4, 12, 4, 31, 0, 26, 116, 91, 0, 9, 16, 110, 0, 41, 0, 7, 4, 12, 32, 110, 0, 130, 0, 4, 1, 12, 16, 110] 

BTW,不要使用input作爲變量名。它影響內置函數input

1

根據您對轉換的數據所做的操作,您可能也有興趣array.array

>>> a = array.array("H", input) 
>>> a.byteswap() 
>>> a.tostring() 
'\x04\x0c\x04\x1f\x00\x1at[\x00\t\x10n\x00)\x00\x07\x04\x0c n\x00\x82\x00\x04\x01\x0c\x10n' 
>>> list(bytearray(a.tostring())) 
[4, 12, 4, 31, 0, 26, 116, 91, 0, 9, 16, 110, 0, 41, 0, 7, 4, 12, 32, 110, 0, 130, 0, 4, 1, 12, 16, 110] 
+0

'byteswap'應該有條件地完成。 (取決於'sys.byteorder') – falsetru

+0

falsetru:這真的取決於OP想要做什麼。 –

+0

我的意思是答案中的代碼在大端系統中不會產生相同的輸出。您添加了'byteswap'來使結果與問題中的'out'匹配。你不是嗎? – falsetru

0

在本SO question指出,你也可以使用一個generator功能:

input_data = [1036, 1055, 26, 29787, 9, 4206, 41, 7, 1036, 8302, 130, 4, 268, 4206] 

def convert(x): 
    for i in x: 
     yield i>>8 
     yield i&0xFF 

print list(convert(input_data)) 

結果

[4, 12, 4, 31, 0, 26, 116, 91, 0, 9, 16, 110, 0, 41, 0, 7, 4, 12, 32, 110, 0, 130, 0, 4, 1, 12, 16, 110] 
相關問題