Home > Mobile >  Python: Access elements of a binary string as if there are no spaces between
Python: Access elements of a binary string as if there are no spaces between

Time:07-15

I have a list of couple like this ('01 0 00 0',key0), ('01 0 11 0',key1), ('01 0 11 1',key2) and I would like to pick the elements with only the third and fourth bit equal to 1. So for example in this case I'll get ('01 0 11 0',key1) and ('01 0 11 1',key2).

How can I pick the couple with these elements ?

CodePudding user response:

You can use a list comprehension:

l = [i for i in list_couples if i[0].split(" ")[2]=="11"]

If the spaces are not always the same:

l = [i for i in list_couples if i[0].replace(" ", "")[3:5]=="11"]

CodePudding user response:

You can just use list comprenhension, like this:

tuples = [('01 0 00 0',key0), ('01 0 11 0',key1), ('01 0 11 1',key2)]

res = [(s, k) for (s, k) in tuples if s.split(' ')[2] == '11']
  • Related