如何在python中查找包含int的列表的索引

时间:2016-12-21 15:19:00

标签: python list

如果我有这份清单

layout_constraintBottom_toBottomOf

我想将myVar设置为包含数字5的列表的索引。最后myVar将等于1.我该怎么做?我是python的新手,所以一个简单的答案将不胜感激。

3 个答案:

答案 0 :(得分:3)

myList = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# loop if 5 in the sub_list, than give the index
myVar = [myList.index(ls) for ls in myList if 5 in ls]
print myVar 
# 1

答案 1 :(得分:1)

使用for - 循环从myList获取子列表,然后检查if 5 in sublist:

这样您就会找到5

的第一行
my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
my_var = None

for number, row in enumerate(my_list):
    if 5 in row:
        my_var = number
        break # don't search in other rows

print(my_var)

如果您需要5的所有行,则列出结果

my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
my_var = [] # list for all results

for number, row in enumerate(my_list):
    if 5 in row:
        my_var.append( number )

print(my_var)

或一行

my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

my_var = [number for number, row in enumerate(my_list) if 5 in row]

print(my_var)

答案 2 :(得分:1)

您可以使用enumerate()创建自定义函数,以获取索引:

def get_index(my_list, val):
    for i, item in enumerate(my_list):
        if val in item:
            return i
    else:
        raise ValueError('{} not found in {}'.format(val, my_list))

示例运行:

>>> myList = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Valid value
>>> get_index(myList, 5)
1

# Invalid value
>>> get_index(myList, 22)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in get_index
ValueError: 22 not found in [[1, 2, 3], [4, 5, 6], [7, 8, 9]]