Python - 在列表列表中查找项目的索引
我有一份清单清单:
colours=[["#660000","#863030","#ba4a4a","#de7e7e","#ffaaaa"],["#a34b00","#d46200","#ff7a04","#ff9b42","#fec28d"],["#dfd248","#fff224","#eefd5d","#f5ff92","#f9ffbf"],["#006600","#308630","#4aba4a","#7ede7e","#aaffaa"]]
搜索列表的最干净方式是什么,并返回其中一个项目的位置,例如#660000
?
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")
给出: ValueError:['#660000']不在列表
中,而不是 [ 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)
这将返回找到第一个元素的元组或无
如果没有找到元素(你也可以删除上面的无
参数如果没有找到元素,它将引发 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正确指出的那样,如果匹配数量很高,这将引入一些开销,因为 color
被迭代两次以找到 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.