Finding the index of an item in a list

后端 未结 30 3389
你的背包
你的背包 2020-11-21 05:28

Given a list [\"foo\", \"bar\", \"baz\"] and an item in the list \"bar\", how do I get its index (1) in Python?

30条回答
  •  一个人的身影
    2020-11-21 05:54

    name ="bar"
    list = [["foo", 1], ["bar", 2], ["baz", 3]]
    new_list=[]
    for item in list:
        new_list.append(item[0])
    print(new_list)
    try:
        location= new_list.index(name)
    except:
        location=-1
    print (location)
    

    This accounts for if the string is not in the list too, if it isn't in the list then location = -1

提交回复
热议问题