[英]How to print out a statement only once in loop
I've got a problem: I've got a sequence of numbers and a number n.我有一个问题:我有一个数字序列和一个数字 n。 I need to write a programm that should output all positions of n in the numerical sequence.我需要编写一个程序,它应该 output 在数字序列中的所有 n 位置。 In case if n is not in the sequence, print the line "not found".如果 n 不在序列中,则打印“未找到”行。 Actually, I have an issue with this "not found".实际上,我对这个“未找到”有疑问。 It's needed to be printed out only onece, but it prints out several times.它只需要打印一次,但它会打印多次。 How can I fix it?我该如何解决?
line = input()
n = input()
line = line.split()
pos_list = []
x = 0
for j in range(len(line)):
pos_list.append(j)
#print(pos_list)
for i in line:
if i == n:
print(line.index(n, x))
else:
print("not found")
x = x + 1
For example for line = 3 5 3 6 4, n = 7 I've got:例如对于 line = 3 5 3 6 4, n = 7 我有:
not found
not found
not found
not found
not found
If I use break
after print("not found")
it always prints not found even n
is in the sequence如果我在print("not found")
之后使用break
它总是打印 not found 即使n
在序列中
Try to "remember" if n was found.如果找到 n,请尝试“记住”。 If not print "not found" once after the loop is done:如果循环完成后未打印一次“未找到”:
line = input()
n = input()
line = line.split()
pos_list = []
x = 0
found = False
for j in range(len(line)):
pos_list.append(j)
#print(pos_list)
for i in line:
if i == n:
print(line.index(n, x))
found = True
x = x + 1
if not found:
print("not found")
You can put this code it works fine:你可以把这段代码正常工作:
line = input()
n = input()
line = line.split()
pos_list = []
x = 0
for j in range(len(line)):
pos_list.append(j)
#print(pos_list)
flag =0
for i in line:
if i == n:
flag=1
print(line.index(n, x))
x = x + 1
if (flag==0):
print("not found")
but if you want to find substrings, then you this code doesn't works.但是如果你想找到子字符串,那么你这个代码不起作用。 You are saperating line string into array of strings by dividing line through spaces: Example:您通过空格分隔线将线串分成字符串数组:示例:
line="hello worldhello helloYou"
n="hello"
so here hello is at location 0 not on 11, 17 position.所以这里你好是在位置 0 而不是在 11、17 position。 Because you are not considering substring因为你没有考虑substring
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.