在嵌套列表中获取子列表的索引位置的最有效方法

时间:2014-06-02 21:03:15

标签: python list indexing nested-lists sublist

我想获得嵌套列表中子列表的索引位置,例如0 对于[1,2] in nested_ls = [[1,2],[3,4]]。获取子列表索引的最优雅方式是什么,是否有类似于index()的内容?

1 个答案:

答案 0 :(得分:5)

是。它被称为index

>>> [[1, 2], [3, 4]].index([1, 2])
0
>>> [[1, 2], [3, 4]].index([3, 4])
1
>>> [[1, 2], [3, 4]].index([1, 5])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: [1, 5] is not in list