所以我得到了一个未排序的列表和两个整数,然后搜索列表中是否有一个值高于其中一个,低于另一个,每次我运行它时,我都会得到“'type'object is not subscribable”,这对我来说绝对没有意义,因为我是一个初学者。。。请帮忙。在
def unsortedSearch(list1, i, u):
found = False
pos = 0
pos2 = 0
while pos < len(list1) and not found:
if list[pos] < u :
if list[pos2] > i:
found = True
pos2 = pos2 + 1
pos = pos + 1
return found
unsortedList = ['1', '3', '4', '2', '6', '9', '2', '1', '3', '7']
num1 = '3'
num2 = '5'
isItThere = unsortedSearch(unsortedList, num1, num2)
if isItThere:
print ("There is a number between those values")
else:
print ("There isn't a number between those values")
您使用list[]iso list1[]。list是python中的一个类型,如错误所示,不能订阅类型
其次,您可以使用列表理解使代码更具可读性
[]之间的部分称为列表理解:基本上会返回一个带有每个if的列表,其中x在num1和num2之间。 因为在Python中空列表是false,(will None、false、0和“”)可以使用if快捷方式
在函数
unsortedSearch
中,有一个名为list1
的参数,但在函数体中,它看起来像是将其称为list
。因此,将您的list
全部改为list1
,您当前的问题将得到解决:在if条件中使用“list”而不是“list1”。在
修改算法:如果我理解得很好,你要在列表中查找I和u之间的值,那么为什么要定义pos和pos2?在
如果要检查i<;list1[pos]<;u,则转到列表中的下一项。在
这足够你写代码了:)
相关问题 更多 >
编程相关推荐