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.
I made a simple list called Names and had variables:
found=False
index=0
I made another variable Searchname that contains a user entered string (a name) although there seems to be an error.
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. 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. it will return True
if that element is present in the list else False
.
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.
The main part is the function index() its syntax is list.index(item) this will give the index of 'item' in 'list'
#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"
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.