Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set and zip questions with Python

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

like image 775
JohnX Avatar asked Oct 04 '12 23:10

JohnX


Video Answer


2 Answers

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.

like image 76
nneonneo Avatar answered Oct 19 '22 00:10

nneonneo


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)].

like image 40
Rajendra Avatar answered Oct 19 '22 01:10

Rajendra