Python使用循环搜索N号并返回索引 [英] Python using a loop to search for N number and return index

查看:52
本文介绍了Python使用循环搜索N号并返回索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总共编程了三个星期.我现在正陷在这个问题上:

我们将为您传递2个输入信息:

数字列表

要查找的数字N

您的工作是在列表中循环查找第二个输入中指定的数字.在找到数字的地方输出列表元素索引.

如果在列表中未找到N,则输出-1.

这是我到目前为止所拥有的:

提供了进口和N

  import sysN = int(sys.argv [2]) 

这也是提供的

  numbers = []对于sys.argv [1] .split(,")中的我:if(i.isdigit()):number.append(int(i)) 

mycode

  i的数字:如果数字为N:打印(i)elif N不是数字:打印(-1) 

这将为随机数输入输出以下内容:

程序输入失败:1,3,11,42,12 2预期输出:-1您的程序输出:-1-1-1-1-1

这不起作用,并且为不在列表编号中的每个数字N返回-1.我曾尝试在打印前后使用break语句,但是这完全使它无法打印.有什么建议么?

解决方案

感谢您的评论和回答.经过一番摸索之后,最终提供了正确的输出:

我的代码:

 如果N个数字:打印(numbers.index(N))如果N不为数字:打印(-1) 

输出:

程序输出

输入:1,3,11,42,12 42您的输出:3挑战反馈

做得好!

I have been programming for a total of three weeks. I am stuck on this problem right now:

We will pass you 2 inputs:

A list of numbers

A number, N, to look for

Your job is to loop through the list and find the number specified in the second input. Output the list element index where you find the number.

If N is not found in the list, output -1.

This is what I have so far:

import and N were provided

import sys
N= int(sys.argv[2])

this is also provided

numbers= []
for i in sys.argv[1].split(","):
    if(i.isdigit()):
        numbers.append(int(i))

mycode

for i in numbers: 
    if N in numbers: 
        print(i)
    elif N not in numbers: 
        print(-1)

This outputs the following for the random number inputs:

Program Failed for Input: 1,3,11,42,12 2 Expected Output: -1 Your Program Output: -1 -1 -1 -1 -1

This is not working and returns -1 for every number N that is not in the list numbers. I have tried using a break statement before and after print, but that stops it from printing at all. Any suggestions?

解决方案

Thank you for your comments and answers. After messing around with it a bit, this is what ended up providing the proper output:

My Code:

if N in numbers: 
    print (numbers.index(N))
if N not in numbers: 
    print(-1) 

Output:

Program Output

Input: 1,3,11,42,12 42 Your Output: 3 Challenge Feedback

Well done!

这篇关于Python使用循环搜索N号并返回索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆