简体   繁体   中英

Retrieving an item from a 2D list

I have a 2D list where each "row" has an index, name, and a path like [(1L, "bar", "foo/bar"), (2L, "app", "some/app"),] etc. I am trying to retrieve a "row" from this 2D list given and index. For example, an index of 1 should return (1L, "bar", "foo/bar") . I know I can loop through my whole list and compare the index until I find the object like so:

my_index = 1    
for row in my_list:
    if (row[0] == my_index)
        return row
return False

I was wondering if there is a cleaner/nicer way to do this in python, since I am new to python. I know there is an index method for a list that returns the index from a list but I'm not sure how I can use that with a 2D list. Thanks in advance! Oh and also, it can be assumed that there will only be one instance of each object (ie: no duplicates)

It looks like you would be better off using a dictionary instead of a list, so your data would look like this:

my_dict = {1L: (1L, "bar", "foo/bar"),
           2L: (2L, "app", "some/app")}

This allows you to efficiently access each element by index:

>>> my_dict[1]
(1L, 'bar', 'foo/bar')

Here is how you could create the dictionary from the list:

my_dict = {row[0]: row for row in my_list}

Or on Python 2.6 and below:

my_dict = dict((row[0], row) for row in my_list)

If your list is static (meaning you are not going to add/remove items from it) you might want to consider sorting your it.

By default, and if I'm not wrong, tuple are sorted by their first element and therefor you should have a sorted list where my_list[x-1] index is x

my_list.sort()
row = my_list[my_index - 1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM