簡體   English   中英

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

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

這可能是一個非常簡單的程序,但我試圖在列表中(在 python 中)找到一個項目,但它似乎不起作用。

我做了一個名為Names的簡單列表,並有變量:

found=False
index=0

我創建了另一個變量Searchname ,其中包含用戶輸入的字符串(名稱),盡管似乎存在錯誤。

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

        print('Found')

    else:
        print('Not found')  

我嘗試在網上搜索答案,但它們真的很復雜,我真的希望這里可能有一些可管理的解決方案。

您可以使用in運算符簡單地檢查一個元素是否存在。

item in my_list

通常要檢查一個項目是否在列表中,您可以像 Python 一樣檢查它。 但這將區分大小寫。 否則,您必須先將列表小寫。

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

您可以使用in運算符來搜索列表中的元素。 如果該元素存在於列表 else False ,它將返回True

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

這是在列表中查找項目索引的最簡單方法之一。 我將用一個例子來解釋這一點。 假設我們有一個水果列表(List_Of_Fruits),我們需要找到一個水果的索引(Fruit_To_Search),我們可以使用給定的代碼。

主要部分是函數 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