Reputation: 23
suppose i have a list of lists [[1,2,3],[1,2,3,4]]
how can I find the xor of all the list of list elements,
since the xor of [1^2^3]
is 0
, xor of [1^2^3^4]
is 4
so the resultant list will be
[0,4]
Thanks in advance.
Upvotes: 2
Views: 615
Reputation: 7113
You can use list comprehension with functools.reduce
and operator.xor
.
from operator import xor
from functools import reduce
seq = [[1,2,3],[1,2,3,4]]
res = [reduce(xor, i) for i in seq]
print(res)
Output
[0, 4]
Edit: To get the "list that has max xor value"
This will return a "list of lists" with all lists whose xor value is the same as that of max_xor
.
max_xor = max(res) # from above
max_xor_lists = [i for i, j in zip(seq, res) if j == max_xor]
print(max_xor_lists)
Output
[[1, 2, 3, 4]]
If you only need the first list that has the maximum xor value, then max_xor_lists[0]
will give the first list that matches this condition.
If the only outcome is to get the list that has the max xor value (IOW, do not want the intermediate xor results) then as suggested by Alex in comments
from operator import xor
from functools import reduce, partial
seq = [[1,2,3],[1,2,3,4]]
_xor = partial(reduce, xor)
max_xor_list = max(seq, key=_xor)
print(max_xor_list)
Output
[1, 2, 3, 4]
Upvotes: 6