Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hash function on list

Tags:

python

hash

I have a list containing 3 fields:

[weight, age, marks]

I would like to apply hash function on each individual row and store these hash values as list. How to proceed with this?

I have combined the individual lists of weight, age, mark using the zip() function:

list1=zip(weight,age,marks)

Kindly help me with this an I am new to python. Thanks in advance.

like image 366
user3577226 Avatar asked Jun 22 '26 13:06

user3577226


1 Answers

You may try to create a hash on tuple structure, like (1, 444, "fine") but not on lists like [1, 444, "fine"] because it is mutable.

In [56]: weight = 120.0

In [57]: age = 99

In [58]: marks = ("a", "b", "cc")

In [59]: row = [weight, age, marks]

Trying hash on mutable structure like list will fail:

In [60]: hash(row)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-60-4a104abdcd18> in <module>()
----> 1 hash(row)

TypeError: unhashable type: 'list'

Tuple is immutable, this will succeed:

In [61]: hash(tuple(row))
Out[61]: 1271481222345795008

Note, that in my example I have created marks as tuple, if you have it as a list, it has to be converted to tuple too:

In [62]: marks = ["a", "b", "cc"]

In [63]: hash((weight, age, marks))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-63-7c8ffc07e716> in <module>()
----> 1 hash((weight, age, marks))

TypeError: unhashable type: 'list'

In [64]: hash((weight, age, tuple(marks)))
Out[64]: 1271481222345795008
like image 74
Jan Vlcinsky Avatar answered Jun 24 '26 02:06

Jan Vlcinsky