简体   繁体   中英

How to find .index of list item within array on python?

I have multiple numbers of list within one singular array, and would like to find out the position of a certain list within the array. This list that I would like the position of would have to contain the word the user enters as the first item of that list.

john = ['John', 'Smith', 'm', 34, 1.7, True]
mary = ['Mary', 'Smith', 'f', 33, 1.54, False]
frank = ['Frank', 'Lee', 'm', 48, 1.83, False]
mark = ['Mark', 'Abbott', 'm', 27, 1.73, True]
jasmine = ['Jasmine', 'Healy', 'f', 19, 1.64, True]
cathy = ['Cathy', 'Potter', 'f', 19, 1.59, True]

LIST = [john, mary, frank, mark, jasmine, cathy]

print("Hello, welcome to the parachutist searcher.")
loop = 0
while loop == 0:
    name = input("Please enter a first name: ")
    if name in [item[0] for item in LIST]:
        finalName = name
        print(finalName)
        position = LIST.index([finalName])
        print(position)
    else:
        print("Nup.")

For some reason when I try and print the position, it returns that it cannot find the finalName in the array. How do I fix this?

You could always use a simple for statement. Formatting it like this would also keep from entering an infinite loop.

name = input("Give me a name.")
found = false
for each in LIST:
    if name in each:
        found = true
        print(name)
        print(LIST.index(each))
if found == false:
    print("nup.")

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM