使用python在2D列表中搜索以找到x,y位置 [英] Search in 2D list using python to find x,y position
本文介绍了使用python在2D列表中搜索以找到x,y位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有2D列表,我需要搜索元素的索引.在我刚开始编程时,我使用了以下功能:
I have 2D list and I need to search for the index of an element. As I am begineer to programming I used the following function:
def in_list(c):
for i in xrange(0,no_classes):
if c in classes[i]:
return i;
return -1
这里的类是2D列表,no_classes表示类的数量,即列表的第1个维度.当c不在araray中时,返回-1.我可以优化搜索吗?
Here classes is a 2D list and no_classes denotes the number of classes i.e the 1st dimesntion of the list. -1 is returned when c is not in the araray. Is there any I can optimize the search?
推荐答案
您不需要自己定义no_classes
.使用enumerate()
:
You don't need to define no_classes
yourself. Use enumerate()
:
def in_list(c, classes):
for i, sublist in enumerate(classes):
if c in sublist:
return i
return -1
这篇关于使用python在2D列表中搜索以找到x,y位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文