iterating quickly through list of tuples

前端 未结 5 1681
清歌不尽
清歌不尽 2020-12-05 06:34

I wonder whether there\'s a quicker and less time consuming way to iterate over a list of tuples, finding the right match. What I do is:

# this is a very lon         


        
5条回答
  •  抹茶落季
    2020-12-05 06:47

    Assuming a bit more memory usage is not a problem and if the first item of your tuple is hashable, you can create a dict out of your list of tuples and then looking up the value is as simple as looking up a key from the dict. Something like:

    dct = dict(tuples)
    val = dct.get(key) # None if item not found else the corresponding value
    

    EDIT: To create a reverse mapping, use something like:

    revDct = dict((val, key) for (key, val) in tuples)
    

提交回复
热议问题