gpt4 book ai didi

python - 搜索函数python

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:14:05 24 4
gpt4 key购买 nike

您好,我正在尝试在 Python 中创建一个搜索函数,它遍历一个列表并在其中搜索一个元素。

到目前为止我得到了

def search_func(list, x)

if list < 0:
return("failure")
else:
x = list[0]

while x > list:
x = list [0] + 1 <---- how would you tell python to go to the next element in the list ?
if (x = TargetValue):
return "success"
else
return "failure"

最佳答案

嗯,您当前的代码不是很 Pythonic。而且有几个错误!您必须使用索引来访问列表中的元素,更正您的代码,如下所示:

def search_func(lst, x):
if len(lst) <= 0: # this is how you test if the list is empty
return "failure"
i = 0 # we'll use this as index to traverse the list
while i < len(lst): # this is how you test to see if the index is valid
if lst[i] == x: # this is how you check the current element
return "success"
i += 1 # this is how you advance to the next element
else: # this executes only if the loop didn't find the element
return "failure"

...但是请注意,在 Python 中您很少使用 while 来遍历列表,一种更自然和更简单的方法是使用 for,它会自动绑定(bind)一个每个元素的变量,而不必使用索引:

def search_func(lst, x):
if not lst: # shorter way to test if the list is empty
return "failure"
for e in lst: # look how easy is to traverse the list!
if e == x: # we no longer care about indexes
return "success"
else:
return "failure"

但我们可以甚至 Pythonic!您要实现的功能非常普遍,已经内置到列表中。只需使用 in 来测试元素是否在列表中:

def search_func(lst, x):
if lst and x in lst: # test for emptiness and for membership
return "success"
else:
return "failure"

关于python - 搜索函数python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19640389/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com