1

I would like to convert this list:

a = [['0001', '0101'], ['1100', '0011']]

to:

a' = [['1110', '1010'],['0011','1100']]

In the second example, every character is changed to its opposite (i.e. '1' is changed to '0' and '0' is changed to '1'). The code I have tried is:

for i in a:
    for j in i:
        s=list(j)
        for k in s:
            position = s.index(k)
            if k=='0':
                s[position] = '1'
            elif k=='1':
                s[position] = '0'
        ''.join(s)

But it doen't work properly. What can I do? Thanks

0

4 Answers 4

2

You can use a function that flips the bits like this:

from string import maketrans

flip_table = maketrans('01', '10')
def flip(s):
    return s.translate(flip_table)

Then just call it on each item in the list like this:

>>> flip('1100')
'0011'
Sign up to request clarification or add additional context in comments.

Comments

0
[["".join([str(int(not int(t))) for t in x]) for x in d] for d in a]

Example:

>>> a = [['0001', '0101'], ['1100', '0011']]
>>> a_ = [["".join([str(int(not int(t))) for t in x]) for x in d] for d in a]
>>> a_
[['1110', '1010'], ['0011', '1100']]

Comments

0

Using a simple list comprehension:

[[k.translate({48:'1', 49:'0'}) for k in i] for i in a]

48 is the code for "0", and 49 is the code for "1".

Demo:

>>> a = [['0001', '0101'], ['1100', '0011']]
>>> [[k.translate({48:'1', 49:'0'}) for k in i] for i in a]
[['1110', '1010'], ['0011', '1100']]

For Python 2.x:

from string import translate, maketrans
[[translate(k, maketrans('10', '01')) for k in i] for i in a]

Comments

0
from ast import literal_eval
import re

a = [['0001', '0101'], ['1100', '0011']]

print literal_eval(re.sub('[01]',lambda m: '0' if m.group()=='1' else '1',str(a)))

literal_eval() is said to be safer than eval()

Comments

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.