[英]Python how do you get the index of a list in a list, by knowing the first element of the list in lists?
Imagine the list [[0, 1],[2, 3][4, 5]],想象一下列表 [[0, 1],[2, 3][4, 5]],
how can I get the index of the list [2,3] (which is supposed to be 1), by knowing the number 2. In code something like:如何通过知道数字 2 来获得列表 [2,3](应该是 1)的索引。在代码中,类似于:
in a list of lists, find the index of the list where list[0] == 2.在列表列表中,找到列表的索引,其中 list[0] == 2。
This should return 1.这应该返回 1。
You can do this using a for loop.您可以使用 for 循环执行此操作。 So for example:例如:
nums = [[0, 1],[2, 3],[4, 5]]
for index, num_list in enumerate(nums):
if num_list[0] == 2:
print(index)
You could use the next function on an enumeration of the list that would return the index of matching items您可以在列表的枚举上使用 next 函数,该函数将返回匹配项的索引
aList = [[0, 1],[2, 3],[4, 5]]
index = next(i for i,s in enumerate(aList) if s[0]==2)
print(index) # 1
or, if you're not concerned with performance, using a more compact way by building a list of the first elements of each sublist and using the index() method on that:或者,如果您不关心性能,可以通过构建每个子列表的第一个元素的列表并在其上使用 index() 方法来使用更紧凑的方法:
index = [*zip(*aList)][0].index(2)
or或者
index = [i for i,*_ in aList].index(2)
Iterate through the list and check the value of the first element.遍历列表并检查第一个元素的值。 Use a variable to track which index you're looking at.使用变量来跟踪您正在查看的索引。
for i in list:
if i[0]==2:
print(list.index(i))
Check Kaggle python course for such practical exercises https://www.kaggle.com/learn/python检查 Kaggle python 课程以获得此类实践练习https://www.kaggle.com/learn/python
Since index
method only supports exact value comparison, you need to iterate.由于index
方法只支持精确值比较,所以需要迭代。 See this question: Python: return the index of the first element of a list which makes a passed function true看到这个问题: Python: return the index of the first element of a list which make a passed function true
array = [[0, 1],[2, 3],[4, 5]]
def get_index(array):
i = 0
for element in array:
if(element[0]==2):
break
i+=1
return i
print(str(get_index(array)))
If you have lots of such queries to make, it might be more efficient to build a dict first, with the first value of each sublist as key and the sublist as value:如果你有很多这样的查询要进行,首先构建一个字典可能更有效,将每个子列表的第一个值作为键,子列表作为值:
data = [[0, 1], [2, 3], [4, 5]]
data_by_first_value = {lst[0]: lst for lst in data}
This dict will look like:这个 dict 看起来像:
print(data_by_first_value)
# {0: [0, 1], 2: [2, 3], 4: [4, 5]}
It is then an O(1) operation to get the sublist you're looking for:然后是一个 O(1) 操作来获取您正在寻找的子列表:
print(data_by_first_value[2])
# [2, 3]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.