在列表列表中查找项目的索引 [英] Find the index of an item in a list of lists

查看:25
本文介绍了在列表列表中查找项目的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表:

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

搜索列表并返回其中一项的位置的最简洁方法是什么,例如"#660000"?

What's the cleanest way of searching the list and returning the position of one of the items, e.g. "#660000"?

我已经查看了 index 方法,但这似乎并没有解开列表中的列表.

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

postion = colours.index("#660000")

给出:ValueError: ['#660000'] is not in list, not [0][0] 正如我所期望的......

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

推荐答案

我会这样做:

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

这将返回一个元组列表,其中第一个索引是第一个列表中的位置,第二个索引是第二个列表中的位置(注意:c 是您要查找的颜色,即,"#660000").

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)

这将返回找到的第一个元素的元组,如果没有找到元素,则返回 None(您也可以删除上面的 None 参数,它会引发一个 StopIteration 如果未找到元素则异常).

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).

正如@RikPoggi 正确指出的那样,如果匹配数很高,这将引入一些开销,因为 colour 被迭代两次以找到 c.我认为这对于少量匹配是合理的,并且可以将答案转换为单个表达式.但是,为了避免这种情况,您也可以使用相同的想法定义一个方法,如下所示:

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')]

请注意,由于 find 是一个生成器,您实际上可以像在上面的示例中使用它使用 next 来停止第一次匹配并跳过进一步查找.

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.

这篇关于在列表列表中查找项目的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆