Not sure why this one works when using set and zip:
>>> a = ([1])
>>> b = ([2])
>>> set(zip(a,b))
{(1, 2)}
but this one doesn't ?.
>>> a = ([1],[2])
>>> b = ([3],[4])
>>> set(zip(a,b))
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
set(zip(a,b))
TypeError: unhashable type: 'list'
Desired result (1,3) (2,4)
What's the right way to do this ?
Thanks!
John
It makes more sense if we look at the zip
output:
>>> a = ([1]) # equivalent to [1], not a tuple
>>> b = ([2]) # equivalent to [2], not a tuple
>>> list(zip(a,b))
[(1, 2)]
>>> a = ([1],[2])
>>> b = ([3],[4])
>>> list(zip(a,b))
[([1], [3]), ([2], [4])]
In the first case, the list contains a tuple of ints; in the second case, it contains tuples of lists and lists are not hashable.
In the first case, if you wanted a singleton tuple containing a list, you should use a = ([1],)
and b = ([2],)
. If you define a
and b
that way, then set(zip(a, b))
will fail like it does in the second case.
You can perform operation like this then you get the desired output.
a = ([1],[2])
b = ([3],[4])
zip(zip(*a),zip(*b))[0]
Like this ((1, 2), (3, 4)).
zip(*a)
convert the all list in a and b tuple variable like [(1,2)] and [(3,4)].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With