cbbcbail
cbbcbail

Reputation: 1771

Python: Check an index against multiple other indexes

I am using Python and I would like to check the location of a value in a list of lists against other indexes.

Like if I had 1 at (1, 1) I would want to be able to check if 1 were at the other indexes so I could make something happen based on which index it matched.

For example:

list_of_lists = [
    [4, 5, 6],
    [7, 1, 8],
    [6, 2, 9]
    ]
if 1 in row for row in list_of_lists:
    if index of 1 is (0, 0), (0, 1), or (0, 2)
        print ("It is in the First row!")
    if index of 1 is (1, 0), (1, 1), or (1, 2)
        print ("It is in the second row!")

If this worked correctly it should print: "It is in the second row!" Because the index of 1 matches with one of the indices in the third if statement. They may not necessarily be rows in some instances where I would be using this. So If you could provide a way that would not use the rows in your answer. Just a way to look at indexes and compare them. Obviously this is not the correct syntax. But how would I do that in Python? How would I get the index of 1 and compare it to other indexes in a list of lists?

Thanks!

Upvotes: 0

Views: 477

Answers (4)

wleao
wleao

Reputation: 2346

trying this in a python file:

list_of_lists = [
    [4, 5, 6],
    [7, 0, 8],
    [6, 2, 9]
]

def index_of(value, matrix):
    for i, r in enumerate(matrix):
        for j, c in enumerate(r):
            if c == value:
                # returns the first instance
                return (i,j)
    return None

if index_of(0, list_of_lists) == (1,1):
    print "hey"

list_of_lists2 = [
    [0, 5, 6],
    [7, 0, 8],
    [0, 2, 9]
]

def indexes_of(value, matrix):
    return [(i,j) for i, r in enumerate(matrix) for j, c in enumerate(r) if c == value]

print indexes_of(0, list_of_lists2)

outputs

hey
[(0, 0), (1, 1), (2, 0)]

[EDIT] As requested:

First of all, what does enumerate do?

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

source

As you can see, if you use enumerate, it will return both the index of the element AND the element. Therefore, while you're iterating over the returned list you can access them and do what you desire. That's what I'm doing here:

for i, r in enumerate(matrix)

In that case, i stands for the row index, and r stands for row itself. ok?

In the next line you do the same thing, but now you're enumerating the row itself, ok? And you're getting, now, the indexes of the values j and the values c that are stored in each row.

Finally, when you return (i,j), you're just returning a tuple that represents the values's matrix index.

Upvotes: 1

Don Question
Don Question

Reputation: 11624

Something like this:

def lindex(list_of_lists, item):
    for l in list_of_lists:
        if item in l:
            return list_of_lists.index(l)

listoflists = [[4, 5, 6], [7, 1, 8], [6, 2, 9]]
item = 1
print "it is in the %. row" % lindex(listoflists, item)

As for your attempt to shortcut with:

if 1 in row for row in list_of_lists:
  1. The syntax is incorrect!
  2. You can't avoid to look into every item of every row of the list - NO shortcut
  3. For a halway valid compromise to 1. you could try something like:

    rows = [i for i in listoflists if 1 in i]

This would at either give you an empty list, meaning there are no items with the value "1" or a list the rows containing "1"!

You could then print all row-indices containing 1 with:

for row in rows:
    print "it is in the %. row" % listoflists.index(row)

Upvotes: 1

snim2
snim2

Reputation: 4079

Here's one way to do it:

>>> for lst in range(len(list_of_lists)):
...     if 1 in list_of_lists[lst]:
...             print "it's in list:", lst
... 
it's in list: 1
>>> 

remember the in operator tests whether a value appears in a list (or list like object).

Here's a second way using the index method (discussed in the comments);

>>> for lst in range(len(list_of_lists)):
...     try:
...             _ = list_of_lists[lst].index(1)
...             print "1 is in list", lst
...     except ValueError:
...             continue
... 
1 is in list 1
>>> 

Upvotes: 1

philofinfinitejest
philofinfinitejest

Reputation: 4047

for i,list in enumerate(list_of_lists, 1):
    if 1 in list:
        if i == 1:
            "it is in the first list"
        elif i == 2:
            "it is in the second list"
        ...

This is a basic implementation. You would want to parameterize this but I'm not sure exactly what your inputs would be.

Upvotes: 0

Related Questions