Python: Return 2 ints for index in 2D lists given item

前端 未结 7 1140
轮回少年
轮回少年 2020-12-04 01:31

I\'ve been tinkering in python this week and I got stuck on something.
If I had a 2D list like this:

myList = [[1,2],[3,4],[5,6]]

and

相关标签:
7条回答
  • 2020-12-04 02:00
    def td(l,tgt):
        rtr=[]
        for sub in l:
            if tgt in sub:
                rtr.append(    (l.index(sub),sub.index(tgt))    )
    
        return rtr        
    
    
    myList = [[1,2],[3,4],[5,6]]
    
    print td(myList,3)
    

    This will return more than one instance of the sub list, if any.

    0 讨论(0)
  • 2020-12-04 02:11

    Try this:

    def index_2d(myList, v):
        for i, x in enumerate(myList):
            if v in x:
                return (i, x.index(v))
    

    Usage:

    >>> index_2d(myList, 3)
    (1, 0)
    
    0 讨论(0)
  • 2020-12-04 02:14

    There is nothing that does this already, unless it's in numpy, which I don't know much about. This means you'll have to write code that does it. And that means questions like "What does [[1, 2], [2, 3], [3, 4]].index(3) return?" are important.

    0 讨论(0)
  • 2020-12-04 02:14

    Try this! this worked for me :)

    def ret_pos(mylist,val_to_find):
        for i in (len(mylist)):
            for j in (len(i)):
                if mylist[i][j]== val_to_find:
                    postn=[i,j]
        return(postn);
    
    0 讨论(0)
  • 2020-12-04 02:16

    Using simple genexpr:

    def index2d(list2d, value):
        return next((i, j) for i, lst in enumerate(list2d) 
                    for j, x in enumerate(lst) if x == value)
    

    Example

    print index2d([[1,2],[3,4],[5,6]], 3)
    # -> (1, 0)
    
    0 讨论(0)
  • 2020-12-04 02:18

    If you are doing many lookups you could create a mapping.

    >>> myList = [[1,2],[3,4],[5,6]]
    >>> d = dict( (j,(x, y)) for x, i in enumerate(myList) for y, j in enumerate(i) )
    >>> d
    {1: (0, 0), 2: (0, 1), 3: (1, 0), 4: (1, 1), 5: (2, 0), 6: (2, 1)}
    >>> d[3]
    (1, 0)
    
    0 讨论(0)
提交回复
热议问题