Skip to content Skip to sidebar Skip to footer

Best Way For Convert Binary List To List Of Chars (of Two Special Char)

i have a special list like this: [0,0,0,1,0,1,0,1,1,1,0,1] I want it map to a char list like: ['+','+','+','-','+','-','+','-','-','-','+','-'] here is some code. it multiplies p

Solution 1:

To answer your original question, here's an efficient way to map a list of 0 & 1 integers to plus and minus signs.

binlist = [0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1]
a = ['+-'[u] for u in binlist]
print(a)

output

['+', '+', '+', '-', '+', '-', '+', '-', '-', '-', '+', '-']

However, as I said above, this may not actually be necessary for your probability calculations.

Here are some other improvements that can be made to your code.

all_combinations=list(itertools.product([0,1],repeat=n))
for binlist in all_combinations:

wastes a lot of RAM. For n = 22, the all_combinations list contains over 4 million 22 item tuples. It's far more efficient to iterate over the output of product directly:

for binlist in itertools.product([0, 1], repeat=n):

In this line:

joint_s2[nan_set[i]]='+'if binlist[i]=='0'else'-'

You test binlist[i] against the string'0', but the binlist tuples contain the integers 0 and 1, not strings, and Python will not automatically convert numeric strings to integers or vice versa.

Another puzzling section is

nr=name.replace('.',' ')
nr_spd=re.split(' ',nr)

Why use regex? Why not just use the built-in str.split method, eg

nr_spd = name.split('.')

OTOH, if your name fields may be separated by one or more spaces as well as by at most a single dot then you can do

nr_spd = name.replace('.', ' ', 1).split()

Post a Comment for "Best Way For Convert Binary List To List Of Chars (of Two Special Char)"