0

I have a list of binary number, its about 100 elements in a list:

a='11010010'
n = 2
split=[a[i:i+n] for i in range(0, len(a), n)]

The result showing like this:

split =['11', '01', '00', '10', '01', '10', '11'.....]

My question is how to assign if else looping for my list? The problem is the list need to updated automatically based on the value of the elements.

For example, if '11'=3*2, '01'=7*4, '00'=5*6, '10'=4*8

And I want my result updated to this:

split =[6,28,30,32,28,32, 6 .....]

Thanks a lot! ;)

2
  • Did you mean a="11010010"? And what is encode? Commented Jul 4, 2018 at 23:07
  • it is a, not encode. Sorry for the typo. split=[a[i:i+n] for i in range(0, len(a), n)] yes..it is a="11010010" Commented Jul 4, 2018 at 23:18

2 Answers 2

1

The problem is the list need to updated automatically based on the value of the elements.

Setting aside the rest of your question, which to me is unclear, you can achieve this goal via a dictionary. First define a dictionary mapping:

d = {'11': 6, '01': 28, '00': 30, '10': 32}

Then, using map or a list comprehension, apply the mapping to the elements of your list:

# map
res = list(map(d.get, split))

# list comprehension
res = [d[i] for i in split]

print(res)

[6, 28, 30, 32, 28, 32, 6]
Sign up to request clarification or add additional context in comments.

1 Comment

This is very helpful. Thank you so much. ;)
0

This is a pretty unclear question, given that encode isn't a standard python function, and saying that '11'=3*2 doesn't make much sense, but I'll try to point you in the right direction here.

A lot of the if-else looping in Python can be done with list comprehensions. These structures allow you to construct lists based on conditions and loops you specify. They tend to have the following structure

[value(i) for i in list if condition else value2(i)]

You can try to use this to solve your problem!

4 Comments

Noted and thank you so much. I will try this code later.
No problem man! If you like my answer, make sure to vote and give best answer as appropriate! (green tick on the left)
In my opinion, this is not recommended if you have multiple if / else conditions. This works for a single replacement but becomes unreadable for multiple.
@jpp I agree. However, I just don't know what exact conditions he wants, so going down the list comprehension route at least gives him a starting point.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.