在仅给定子列表 (Python) 的元素的情况下,查找列表中元素索引的最有效方法是什么
What is the most efficient way to find the index of an element in a list, given only an element of a sublist (Python)
即是否存在类似下面的内容?
lst = [["a", "b", "c"], [4,5,6],"test"]
print getIndex(lst, "a")
>>> 0
print getIndex(lst, 5)
>>> 1
print getIndex(lst, "test")
>>> 2
我知道常规的 index() 方法,但它只查找直接元素。我有一个粗略的解决方案,可以制作一个新列表,解析超级列表并添加 "y" 或 "n" 然后在其中寻找 "y" 的索引,但我觉得有很多更好的方法。谢谢
def getIndex(lst,item):
for n,i in enumerate(lst):
if (type(i) == list and item in i) or i == item
return n
getIndex(lst,'test')
>>> 2
使用发电机
例如在 >= Python 2.6 中,如果您知道该项目存在于子列表中:
idx = next(i for i,v in enumerate(lst) if item in v)
尝试对列表使用默认函数:list.index
l = [[1,2,3], ['a', 'b', 'c']]
l[0].index(2) # index 1
l[1].index('b') # index 1
This generates a "ValueError" if the item does not exist.
hellpanderrr's solution 有问题。它假定主要列表元素只是列表或字符串。如果在主列表中有另一种类型的列表中进行搜索(in
操作引发 TypeError
),它将失败。例如:
lst2 = [["a", "b", "c"], [4, 5, 6], "test", 19]
>>> getIndex(lst2, 19)
# Ugly TypeError stack trace ensues
解决这个问题:
def getIndex2(lst, item):
for n, i in enumerate(lst):
try:
if item == i or item in i:
return n
except TypeError:
pass
return None
现在:
>>> getIndex2(lst2, "test")
2
>>> getIndex2(lst2, 19)
3
有几种方法可以完成 "equals or in" 测试。当 i
上的 in
不适合类型时,这个解决方案直接通过,使用 "get forgiveness not permission" 习语来捕捉时间。也可以在in
操作前测试i
的类型,或者直接询问i
是否支持in操作。但是直接类型检查通常不受欢迎,Python 中的字符串和容器具有一些复杂的重叠功能。 "get forgiveness" 方法可以更简单地优雅地处理这些问题。
请注意,这也明确处理了找不到值的情况。
>>> print getIndex2(lst2, 333)
None
虽然函数不return隐含地 return None
,但最好明确说明此类默认情况。
顺便说一句,这种方法处理两个级别。如果列表可以任意嵌套,则需要一种不同的方法,可能涉及递归。
即是否存在类似下面的内容?
lst = [["a", "b", "c"], [4,5,6],"test"]
print getIndex(lst, "a")
>>> 0
print getIndex(lst, 5)
>>> 1
print getIndex(lst, "test")
>>> 2
我知道常规的 index() 方法,但它只查找直接元素。我有一个粗略的解决方案,可以制作一个新列表,解析超级列表并添加 "y" 或 "n" 然后在其中寻找 "y" 的索引,但我觉得有很多更好的方法。谢谢
def getIndex(lst,item):
for n,i in enumerate(lst):
if (type(i) == list and item in i) or i == item
return n
getIndex(lst,'test')
>>> 2
使用发电机
例如在 >= Python 2.6 中,如果您知道该项目存在于子列表中:
idx = next(i for i,v in enumerate(lst) if item in v)
尝试对列表使用默认函数:list.index
l = [[1,2,3], ['a', 'b', 'c']]
l[0].index(2) # index 1
l[1].index('b') # index 1
This generates a "ValueError" if the item does not exist.
hellpanderrr's solution 有问题。它假定主要列表元素只是列表或字符串。如果在主列表中有另一种类型的列表中进行搜索(in
操作引发 TypeError
),它将失败。例如:
lst2 = [["a", "b", "c"], [4, 5, 6], "test", 19]
>>> getIndex(lst2, 19)
# Ugly TypeError stack trace ensues
解决这个问题:
def getIndex2(lst, item):
for n, i in enumerate(lst):
try:
if item == i or item in i:
return n
except TypeError:
pass
return None
现在:
>>> getIndex2(lst2, "test")
2
>>> getIndex2(lst2, 19)
3
有几种方法可以完成 "equals or in" 测试。当 i
上的 in
不适合类型时,这个解决方案直接通过,使用 "get forgiveness not permission" 习语来捕捉时间。也可以在in
操作前测试i
的类型,或者直接询问i
是否支持in操作。但是直接类型检查通常不受欢迎,Python 中的字符串和容器具有一些复杂的重叠功能。 "get forgiveness" 方法可以更简单地优雅地处理这些问题。
请注意,这也明确处理了找不到值的情况。
>>> print getIndex2(lst2, 333)
None
虽然函数不return隐含地 return None
,但最好明确说明此类默认情况。
顺便说一句,这种方法处理两个级别。如果列表可以任意嵌套,则需要一种不同的方法,可能涉及递归。