Python - find the index of an item in a list of li

2019-01-17 23:39发布

I have a list of lists:

colours=[["#660000","#863030","#ba4a4a","#de7e7e","#ffaaaa"],["#a34b00","#d46200","#ff7a04","#ff9b42","#fec28d"],["#dfd248","#fff224","#eefd5d","#f5ff92","#f9ffbf"],["#006600","#308630","#4aba4a","#7ede7e","#aaffaa"]]

whats the cleanest way of search the list, and returning the position of one of the items, e.g. "#660000"?

I have looked at the index method, but that doesn't seem to unpack the list inside the list.

postion=colours.index("#660000")

gives: ValueError: ['#660000'] is not in list, not [0][0] as I expect...

6条回答
叛逆
2楼-- · 2019-01-17 23:57

another thing you can do is selecting the section of the list you want and then use index to find it

list_name[0].index("I want coffee")
查看更多
仙女界的扛把子
3楼-- · 2019-01-18 00:04

I'd do something like this:

[(i, colour.index(c))
 for i, colour in enumerate(colours)
 if c in colour]

This will return a list of tuples where the first index is the position in the first list and second index the position in the second list (note: c is the colour you're looking for, that is, "#660000").

For the example in the question, the returned value is:

[(0, 0)]

If you just need to find the first position in which the colour is found in a lazy way you can use this:

next(((i, colour.index(c))
      for i, colour in enumerate(colours)
      if c in colour),
     None)

This will return the tuple for the first element found or None if no element is found (you can also remove the None argument above in it will raise a StopIteration exception if no element is found).

Edit: As @RikPoggi correctly points out, if the number of matches is high, this will introduce some overhead because colour is iterated twice to find c. I assumed this to be reasonable for a low number of matches and to have an answer into a single expression. However, to avoid this, you can also define a method using the same idea as follows:

def find(c):
    for i, colour in enumerate(colours):
        try:
            j = colour.index(c)
        except ValueError:
            continue
        yield i, j

matches = [match for match in find('#660000')]

Note that since find is a generator you can actually use it as in the example above with next to stop at the first match and skip looking further.

查看更多
狗以群分
4楼-- · 2019-01-18 00:05

If you want to evade from iterating the target sublist twice, it seems that the best (and the most Pythonic) way to go is a loop:

def find_in_sublists(lst, value):
    for sub_i, sublist in enumerate(lst):
        try:
            return (sub_i, sublist.index(value))
        except ValueError:
            pass

    raise ValueError('%s is not in lists' % value)
查看更多
Evening l夕情丶
5楼-- · 2019-01-18 00:09

Using enumerate() you could write a function like this one:

def find(target):
    for i,lst in enumerate(colours):
        for j,color in enumerate(lst):
            if color == "#660000":
                return (i, j)
    return (None, None)
查看更多
Melony?
6楼-- · 2019-01-18 00:09

In Python 3, I used this pattern:

CATEGORIES = [   
    [1, 'New', 'Sub-Issue', '', 1],
    [2, 'Replace', 'Sub-Issue', '', 5],
    [3, 'Move', 'Sub-Issue', '', 7],
]

# return single item by indexing the sub list
next(c for c in CATEGORIES if c[0] == 2)
查看更多
唯我独甜
7楼-- · 2019-01-18 00:21

It would be perhaps more simple using numpy:

>>> import numpy
>>> ar = numpy.array(colours)
>>> numpy.where(ar=="#fff224")
(array([2]), array([1]))

As you see you'll get a tuple with all the row and column indexes.

查看更多
登录 后发表回答