简体   繁体   English

如何在列表中搜索项目 - python

[英]How can you search for an item in a list - python

This is probably a very simple program but I tried to find an item in a list (in python) and it just doesn't seem to work.这可能是一个非常简单的程序,但我试图在列表中(在 python 中)找到一个项目,但它似乎不起作用。

I made a simple list called Names and had variables:我做了一个名为Names的简单列表,并有变量:

found=False
index=0

I made another variable Searchname that contains a user entered string (a name) although there seems to be an error.我创建了另一个变量Searchname ,其中包含用户输入的字符串(名称),尽管似乎存在错误。

while found==False and index<=(len(Names)-1):
    index=index + 1
    if Searchname==Names[index]:
        found=True

        print('Found')

    else:
        print('Not found')  

I tried searching for an answer online but they were really complicated and I really hope that there might be some manageable solutions here.我尝试在网上搜索答案,但它们真的很复杂,我真的希望这里可能有一些可管理的解决方案。

您可以使用in运算符简单地检查一个元素是否存在。

item in my_list

Generally to check if an item is in a list you could as Python to check for that.通常要检查一个项目是否在列表中,您可以像 Python 一样检查它。 But this would be case-sensitive.但这将区分大小写。 Otherwise you would have to lowercase the list first.否则,您必须先将列表小写。

names = ['Mike', 'John', 'Terry']
if 'Mike' in names:
    print ("Found")
else:
    print ("Not Found")

You can use the in operator to search elements in a list.您可以使用in运算符来搜索列表中的元素。 it will return True if that element is present in the list else False .如果该元素存在于列表 else False ,它将返回True

if Searchname in Names:
    found=True
    print('Found')
else:
    print('Not found')

This is one of the simplest ways to find the index of an item in a list.这是在列表中查找项目索引的最简单方法之一。 I'll use an example to explain this.我将用一个例子来解释这一点。 Suppose we have a list of fruits(List_Of_Fruits) and we need to find the index of a fruit(Fruit_To_Search),we can use the given code.假设我们有一个水果列表(List_Of_Fruits),我们需要找到一个水果的索引(Fruit_To_Search),我们可以使用给定的代码。

The main part is the function index() its syntax is list.index(item) this will give the index of 'item' in 'list'主要部分是函数 index() 它的语法是 list.index(item) 这将给出 'list' 中 'item' 的索引

 #A list with a bunch of items(in this case fruits) List_Of_Fruits = ["Apples" , "Bananas" , "Cherries" , "Melons"] #Getting an input from the user Fruit_To_Search = input() #You can use 'in' to check if something is in a list or string if Fruit_To_Search in List_Of_Fruits: #If the fruit to find is in the list, Fruit_Index = List_Of_Fruits.index(Fruit_To_Search) #List_Of_Fruits.index(Fruit_to_Search) gives the index of the variable Fruit_to_Search in the list List_Of_Fruits print(Fruit_To_Search,"exists in the list. Its index is - ",Fruit_Index) else: print(Fruit_To_Search,"does not exist in the list"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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