如何从列表中搜索项目?

2024-04-18 14:40:06 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能告诉我为什么这个代码不能工作吗?你知道吗

list=[5,9,2,5,13] 
item=input("Please enter the search item.")
found=false
for search = 0 to list.length -1
if item==list[search]:
found= True
next search
if found==True:
print("The item is in the list.")
else:
    print("The item is not in the list.")

Tags: the代码intrueinputsearchifis
3条回答

你至少应该用更好的方式写,比如:

lst=[5,9,2,5,13] 
item = int(input("Please enter the search item."))
found = False
for search in range(len(lst)):
    if item == (lst[search]):
        found = True
if found:
    print('{} is in the list'.format(item))
else:
    print('{} is not in the list'.format(item)) 

这就是你想要的:

value = int(input('Please enter a value to search: '))

if value in [5, 9, 2, 5, 13]:
    print('Item found.')
else:
    print('Item not found.')

我不确定它的语法,也不确定它是否真的是python。我建议你先看看教程。你知道吗

但是,您可以这样搜索列表中的元素:

list=[5,9,2,5,13] 
element = raw_input("Please enter the desired element")

if int(element) in list:  #note i've put int() because your list is made out of numbers rather than strings.
    print element + " is in the list"
else:
    print element + " is not in the list"

相关问题 更多 >