Break each item in a list

Is it possible to separate items in a list and generate a new list on the fly? basically I get a ushort list and want to create an ubytes list:

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]

I can easily generate a list of tuples, but how can I delete tuples and merge them into one big list?

out_temp = [(x>>8, x&0xFF) for x in input]
+3
source share
3 answers

You can use list comprehension as follows:

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

or using 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, do not use inputas a variable name. It obscures the built-in function input.

+6
source

Depending on what you want to do with the converted data, you may also be interested 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]
+1
source

SO > , 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]
0

All Articles