在Python中找到列表中元素的索引的好方法是什么? 注意,列表可能没有排序。
是否有方法指定要使用的比较运算符?
在Python中找到列表中元素的索引的好方法是什么? 注意,列表可能没有排序。
是否有方法指定要使用的比较运算符?
有索引方法,i = array.index(value),但我不认为你可以指定一个自定义比较运算符。不过,编写自己的函数来实现这一点并不难:
def custom_index(array, compare_function):
for i, v in enumerate(array):
if compare_function(v):
return i
最好的方法可能是使用列表方法。index。
对于列表中的对象,你可以这样做:
def __eq__(self, other):
return self.Value == other.Value
您需要的任何特殊处理。
你也可以在enumerate(arr)中使用for/in语句
使用实例查找值为> 100的项的索引。
for index, item in enumerate(arr):
if item > 100:
return index, item
源
来自Dive Into Python:
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> li.index("example")
5
列表的索引方法将为您完成此工作。如果想要保证顺序,请先使用sorted()对列表进行排序。Sorted接受cmp或key参数来指示如何进行排序:
a = [5, 4, 3]
print sorted(a).index(5)
Or:
a = ['one', 'aardvark', 'a']
print sorted(a, key=len).index('a')
这个怎么样?
def global_index(lst, test):
return ( pair[0] for pair in zip(range(len(lst)), lst) if test(pair[1]) )
用法:
>>> global_index([1, 2, 3, 4, 5, 6], lambda x: x>3)
<generator object <genexpr> at ...>
>>> list(_)
[3, 4, 5]
下面是另一种使用列表理解的方法(有些人可能会觉得有争议)。对于简单的测试,例如比较对象属性(我需要很多)是非常容易的:
el = [x for x in mylist if x.attr == "foo"][0]
当然,这假设列表中存在一个合适的元素(实际上是惟一性)。
如果你只是想知道一个元素是否包含在列表中:
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> 'example' in li
True
>>> 'damn' in li
False
我通过改编一些教程发现了这一点。感谢谷歌,也感谢你们所有人;)
def findall(L, test):
i=0
indices = []
while(True):
try:
# next value in list passing the test
nextvalue = filter(test, L[i:])[0]
# add index of this value in the index list,
# by searching the value in L[i:]
indices.append(L.index(nextvalue, i))
# iterate i, that is the next index from where to search
i=indices[-1]+1
#when there is no further "good value", filter returns [],
# hence there is an out of range exeption
except IndexError:
return indices
一个非常简单的用法:
a = [0,0,2,1]
ind = findall(a, lambda x:x>0))
[2, 3]
附言:抱歉我的英语不好
我使用function返回匹配元素的索引(Python 2.6):
def index(l, f):
return next((i for i in xrange(len(l)) if f(l[i])), None)
然后使用它通过lambda函数检索所需的元素所需的任何方程,例如通过使用元素名称。
element = mylist[index(mylist, lambda item: item["name"] == "my name")]
如果我需要在我的代码中的几个地方使用它,我只是定义特定的查找函数,例如通过名称查找元素:
def find_name(l, name):
return l[index(l, lambda item: item["name"] == name)]
然后它非常简单易读:
element = find_name(mylist,"my name")