If I have this list of lists
myList = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
and I would like to set myVar equal to the index of the list that contains the number 5. In the end myVar would equal 1. How would I do that? I am new to python so a simple answer would be appreciated.
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
Use for
-loop to get sublist from myList
and then check if 5 in sublist:
This way you find first row with 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)
if you need all rows with 5
then you list for results
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)
or in one line
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)
You may create a custom function using enumerate()
to get the index as:
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))
Sample run:
>>> 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]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.