简体   繁体   中英

Insert value dynamically in 2D list python

I am having a two dimensional list like:

[[1, 1, 0, 0], [1, 0, 1, 0], [0, 1, 1, 0], [1, 1, 1, 0], [1, 1, 1, 0], [0, 1, 1, 0], [1, 1, 1, 1]]

and I want to XOR the inner sub-lists with each other. So at some point of time with some combination I will be getting a sub list with all zeros like [0,0,0,0] and if I don't get with two sub lists I have to go for XORing of three sub-lists till I get again [0,0,0,0] , if not then, have to go for four sub-lists.

The problem is I can do like picking up two lists and XOR each element then save it in separate sub-list and this works but each time I have to change my code so is there any way to XOR sub-list like [1, 1, 0, 0] ^ [1, 0, 1, 0] instead of doing like lis[i][j]^lis[i+1][j] so that I can manage my code recursively?

What you could do is to convert the 2-D bit lists to a 1-D number list and then XOR them together.

a = [[1, 1, 0, 0], [1, 0, 1, 0], [0, 1, 1, 0], [1, 1, 1, 0], [1, 1, 1, 0], [0, 1, 1, 0], [1, 1, 1, 1]]
b = map(lambda x: int("".join(map(lambda y: str(y), x)),2), a)


b is now: [12, 10, 6, 14, 14, 6, 15]

Now you are working with a 1-D list which will make that easier.

You could find shorter but I think this would work:

STOP=[0,0,0,0]

def nxor(l,res=None,p=1):
    if not res: res= l[0]
    if res == STOP:
        return p-1 # or l[:p]
    try:
        return nxor(l,list(iter.imap (operator.xor, *list([res,l[p]]) )),p+1)
    except:
        return None # or res 

print nxor (l)

It returns the position of the last sub-list that lead to [0,0,0,0]; it would be easy to return the sub-list instead, or the actual result (see comments).

If you want to test all the combinations, you could use itertools:

for i in xrange(2,len(l)):
    for j in itertools.combinations(l,i):
        print nxor(list(j))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM