繁体   English   中英

如何在循环中只打印一次语句

[英]How to print out a statement only once in loop

我有一个问题:我有一个数字序列和一个数字 n。 我需要编写一个程序,它应该 output 在数字序列中的所有 n 位置。 如果 n 不在序列中,则打印“未找到”行。 实际上,我对这个“未找到”有疑问。 它只需要打印一次,但它会打印多次。 我该如何解决?

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

例如对于 line = 3 5 3 6 4, n = 7 我有:

not found
not found
not found
not found
not found

如果我在print("not found")之后使用break它总是打印 not found 即使n在序列中

如果找到 n,请尝试“记住”。 如果循环完成后未打印一次“未找到”:

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")

你可以把这段代码正常工作:

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")

但是如果你想找到子字符串,那么你这个代码不起作用。 您通过空格分隔线将线串分成字符串数组:示例:

line="hello worldhello helloYou"
n="hello"

所以这里你好是在位置 0 而不是在 11、17 position。 因为你没有考虑substring

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM