Integer manipulation with python
I have an integer that looks like
a = 1010101010010100
that I would like to turn into something like this
list = [[1,0,1,0],[1,0,1,0],[1,0,0,1],[0,1,0,0]]
What I was trying to do is something like
b = str(a)
list1 = [];
for x in b:
if b.index(x)==0:
tmp_list = [];
if b.index(x)!=0%3:
tmp_list.append(x):
if b.index(x)==0%3 & b.index(x)!=0:
list1.append(tmp_list)
tmp_list=[];
I am not getting the result as expected.
source to share
If you want to split your sequence in groups of 4, you can simply do:
>>> b='1010101010010100'
>>> [b[i:i+4] for i in range(0, len(b), 4)]
['1010', '1010', '1001', '0100']
or wrap the element in list(..)
if you want exactly a list of lists:
>>> [list(b[i:i+4]) for i in range(0, len(b), 4)]
[['1', '0', '1', '0'], ['1', '0', '1', '0'], ['1', '0', '0', '1'], ['0', '1', '0', '0']]
also, if the items in the sublists are to be int
:
>>> [list(int(c) for c in b[i:i+4]) for i in range(0, len(b), 4)]
[[1, 0, 1, 0], [1, 0, 1, 0], [1, 0, 0, 1], [0, 1, 0, 0]]
source to share
You have a lot of problems in your code -
-
I think what you want to do is -
b.index(x)%3 == 0
and notb.index(x)!=0%3
(which doesn't make much sense and is always false, unless b.index (x) is 0. -
You have a colon in the line -
tmp_list.append(x):
this is a syntax error (you should probably remove it). -
&
is a bitwise and operator in python, I suppose you should useand
instead&
. -
list.index(<element>)
gives the first index at which the element exists, since your string only consists of 1s and 0s, this will never go past index 2. Instead, you should consider usingenumerate
that will give you the index as well as the value of the element.
Sentence -
-
You don't have to have a condition
if b.index(x)==0:
, you can just define temp_list outside of the for loop. -
Use
if/elif
(instead of allif
s).
Sample code -
b = str(a)
list1 = []
tmp_list = []
for i,x in enumerate(b):
if i%4!=0 or i==0:
tmp_list.append(x)
else:
list1.append(tmp_list)
tmp_list=[]
tmp_list.append(x)
output -
[['1', '0', '1', '0'], ['1', '0', '1', '0'], ['1', '0', '0', '1']]
source to share
One of the effective solutions could be this: itertools receipes
It returns an iterator, so it should be pretty fast.
from itertools import izip_longest
def grouper(iterable, n, fillvalue=None):
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
numbers = str(1010101010010100)
nth = 3
result = grouper(numbers, nth)
source to share