简体   繁体   English

在代码搜索完列表并且找不到列表中的单词从而答复错误后,如何打印?

[英]How do you print after the code is done searching through the list and it can't find the word in the list so it replies error?

I have a for loop so it can go through the whole list but how do I input for like the very last line that there is no star named Bob and say that it is an error? 我有一个for循环,因此它可以遍历整个列表,但是我如何像最后一行那样输入,因为没有名为Bob的星星,并说这是错误?

big_str = "0.998448,0.035746,-0.042707,352,6.18,14\n0.873265,0.031968,0.486196,358,2.07,15,ALPHERATZ\n0.512379,0.020508,0.858515,432,2.28,21,CAPH\n0.883455,0.044652,-0.466383,720,5.41,34\n0.963482,0.055705,0.261913,886,2.83,39,ALGENIB\n0.752989,0.044458,0.656529,905,5.71,41"

def getStarString(n):
  line_list = big_str.split("\n")
  for x in line_list:
    y = getStarName(x)
    if y == "None":
        continue
    else:
        if y == n:
            print(x)
        if y != n:
            continue
            if y != n:
                print("ERROR: No star called " + n + " could be found.")
def getStarName(name):
  names = list(name.split(","))
  for i in range(0, len(names)):
    if len(names) == 7:
        x = names[6]
        return x
    else:
        return "None"

getStarString("ALGENIB")
getStarString("BOB")

getStarString may be correct as follows: getStarString可能是正确的,如下所示:

def getStarString(n):
  line_list = big_str.split("\n")
  for x in line_list:
    y = getStarName(x)
    if y == "None":
        continue
    elif y == n:
            print(x)
            return
  print("ERROR: No star called " + n + " could be found.")

The output is: 输出为:

0.963482,0.055705,0.261913,886,2.83,39,ALGENIB
ERROR: No star called BOB could be found.

Break out of the loop when you find a match. 找到匹配项时跳出循环。 Then use the else: clause of for to print a message if it ended without breaking. 然后,使用forelse:子句打印一条消息,如果该消息未中断则结束。

def getStarString(n):
  line_list = big_str.split("\n")
  for x in line_list:
    y = getStarName(x)
    if y != "None" and y == n:
        print(x)
        break
  else:
    print("ERROR: No star called " + n + " could be found.")

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

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