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))发布于 2017-09-12 15:58:00
现在,您将字符串传递给搜索。迭代输入字符串中的字符,并检查一个字符是否等于第二个字符串。考虑到这一点:
'12345'[2] == '3'将value转换为int
value = int(input('enter the element to be searched'))将整数传递给搜索,而不是输入:
i = search(input_numbers_list, value)发布于 2017-09-12 16:31:54
丹尼尔用你的问题解决了你的问题,我只是想增加另一种方式来完成你的功能。有一个名为枚举的内置方法,它返回索引和项,您可以将其分配给如下所示的变量:
for index,item in enumerate(somelist):
if item == 'dragon':
print('The dragon was found in the following index: {}'.format(index))要添加的另一件事是使用拆分属性。您应该明确说明要如何拆分字符串。我最喜欢用逗号,但你也可以用空格。
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(' ') ]https://stackoverflow.com/questions/46180708
复制相似问题