def search(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
num=input("enter the elements\n")
input_numbers_list = [int(n) for n in num.split()]
value=input("enter the element to be searched")
print(input_numbers_list)
print(value)
i = search(num,value)
if i is -1:
print("element not found")
else:
print("element found at specific position "+str(i))
答案 0 :(得分:1)
现在您将字符串传递给搜索。迭代输入字符串中的字符,并检查字符是否等于第二个字符串。考虑一下:
'12345'[2] == '3'
将value
转换为int
:
value = int(input('enter the element to be searched'))
将整数传递给搜索,而不是输入:
i = search(input_numbers_list, value)
答案 1 :(得分:0)
Danil把你解决了问题,我只想添加另一种方法来完成你的功能。有一个名为enumerate的内置方法,它返回可以分配给变量的索引和项:
for index,item in enumerate(somelist):
if item == 'dragon':
print('The dragon was found in the following index: {}'.format(index))
要添加的另一件事是使用split属性。您应该明确说明要如何拆分字符串。我最喜欢的是逗号,但你也可以使用空格。
somelist = input('Enter your items comma separated\n')
somelist = [ i for i in somelist.split(',') ]
或
somelist = input('Enter your items space seperated\n')
somelist = [ i for i in somelist.split(' ') ]