I have a list of 16 elements [a00,a01,a02,...,a15] and would like to compute a list [b0,b1,b2,b3,b4,b5,b6,b7] where
b0 = a00*256+a01
b1 = a02*256+a03
b2 = a04*256+a05
(etc.)
what's the easiest way of doing this? (I'm a beginner in python)
I have a list of 16 elements [a00,a01,a02,...,a15] and would like to compute a list [b0,b1,b2,b3,b4,b5,b6,b7] where
b0 = a00*256+a01
b1 = a02*256+a03
b2 = a04*256+a05
(etc.)
what's the easiest way of doing this? (I'm a beginner in python)
b_list = [a_list[2*i] * 256 + a_list[2*i+1] for i in range(8)]
Note that this only works if a has 16 elements.
A more general solution would be:
b_list = [a_list[2*i] * 256 + a_list[2*i+1] for i in range(len(a_list) / 2)]
as long as a_list
has an even number of elements.
The first thing that comes to mind:
>>> a=range(16)
>>> b=[a[i]*256+a[i+1] for i in range(0,len(a),+2)]
[1, 515, 1029, 1543, 2057, 2571, 3085, 3599]
You can make a comprehension list...
a = [a00, a01,.... ]
#Readed, take a list with 0,2,4... len(a) [15, will stop at 14]
# then make a[i]*256 + a[i+1], so
# a[0]*256+a[1], a[2]*256+a[3], ... a[14]*256+a[15]
b = [ a[i]*256+a[i+1] for i in range(0,len(a),2) ]
What the other two answers suggest is called a "List Comprehension", basically it is the same as doing this:
a = range(16)
b = []
for i in range(0, len(a),2):
b.append(a[i]*256+a[i+1])
It just does it in one line.
lst = [a01, a02, ... ]
result = [256 * a + b for a, b in zip(lst[::2], lst[1::2])]
This avoids the unpythonic use of range
.
Not to get too golfy, but if you'd like to avoid subscript hell, you can use this handy zip
idiom:
a = range(16)
b = [x*256+y for x,y in zip(*[iter(a)]*2)]