0

I've gotten some great responses to my questions here, so I'm really grateful for this resource of programmers on this website. I've been working on an algorithm and am almost completed with it, but I'm finding out the very last steps are the most difficult for me because they require very specific things and the wealth of information is so difficult to search through- especially now that my brain is completely fried from learning python (my first language) from scratch a little over a week ago and coding nearly everyday since full time. So, my new, and possibly last (but never say never) problem I need help solving in python is:

The general problem is: How can I return a key value from a list? I'm sure there's something easy I'm overlooking, but the devil is in the details.

The specific problem I'm facing is: Given a nested list L1=[[a,b,c],[d,e,f],[e,a,g]] and value=x, if x=a, where in the list does it occur? so for a=L1[0][0] and a=L1[2][1], the answer should be [[[0],[0]],[[2],[1]]] or actually- we can ignore the big nest- i just need an answer of [[0],[1]] and nothing more.

Thanks!

2
Contributors
1
Reply
2
Views
8 Years
Discussion Span
Last Post by masterofpuppets
0

hi
try something like this:

l = [ [ "a", "b", "c" ], [ "d", "e", "f" ], [ "e", "a", "g" ] ]
value = "a"
valPos = []

for i in range( len( l ) ): # loops through the big list
    for j in range( len( l[ i ] ) ): # loops through each of the nested lists
        if l[ i ][ j ] == value:
            valPos += [ [ i, j ] ] # stores the position of the value occurance
print valPos

#or

l = [ [ "a", "b", "c" ], [ "d", "e", "f" ], [ "e", "a", "g" ] ]
value = "a"
valPos = []

for i in range( len( l ) ): # loops through the big list
    for j in range( len( l[ i ] ) ): # loops through each of the nested lists
        if l[ i ][ j ] == value:
            valPos += [ [ [ i ], [ j ] ] ] # stores the position of the value occurance
print valPos

#output >>
#first piece of code:
>>>[[0, 0], [2, 1]]

#second piece of code:
>>>[[[0], [0]], [[2], [1]]]

hope this helps you :)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.