I have this code:
binary = '011010'
binary = list(map(''.join, zip(*[iter(binary)]*3)))
b=[]
for h in range(len(binary)):
for i in range(len(binary[h])-1):
c = binary[h][i:i+2]
b.append(c)
where i get the result:
binary = ['011', '010']
b = ['01', '11', '01', '10']
And I would like to get an effect:
b = [['01', '11'], ['01', '10']]
So I would like to first take binary[0] and make a loop and then next binary[1] and add the results to list 'b', but in separate sub-lists. While in the above code, it saves the results one by one in the list 'b'.
How can this be done? Ideally, sub-lists should be creating in the loop.
Here's the simple way
b=[]
for h in range(len(binary)):
inner = []
for i in range(len(binary[h])-1):
c = binary[h][i:i+2]
inner.append(c)
b.append(inner)
Or you could use a list comprehension
b = [[binary[h][i:i+2] for i in range(len(binary[h])-1)] for h in range(len(binary)) ]
You can do this with nested list comprehension:
b = [ [ binary[h][i:i+2] for i in range(len(binary[h])-1)]
for h in range(len(binary))]
So here for every value h in range(len(binary)) we construct a separate list, with the list comprehension [ binary[h][i:i+2] for i in range(len(binary[h])-1)]. This list comprehension will let a variable i iterate over range(len(binary[h])-1) and for every element, add binary[h][i:i+2] to the sublist.
That being said, we can improve the code, and iterate over the elements of binary directly:
b = [ [ subbin[i:i+2] for i in range(len(subbin)-1)]
for subbin in binary]
So here for every subbin list in binary, we generate a sublist (again with list comprehension), this is the result of [ subbin[i:i+2] for i in range(len(subbin)-1)] so we generate a list of subbin[i:i+2]s for every i in range(len(subbin)-1).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With