Elif语句打印的时候不应该

时间:2018-05-03 05:16:47

标签: python python-3.x

这是我们高中计算机程序设计课程的一部分。这些是说明。 https://prospect.schoolloop.com/file/1407107943880/1376109333800/2888156401519472863.pdf

for i in glob.glob(train_path + '/*.[tT][iI][fF]'):
    train_list.append(abspath(i))
print(len(train_list))
for i in train_list:
    # print(i)
    img = cv2.imread(i, cv2.IMREAD_GRAYSCALE)

    train_img.append(img.astype(np.float32)/255.0)
train_img = np.array(train_img)
print(train_img)

例如:

def c7():
    myList = [7, 10, 94, 2, 54, 2, 19, 4, 11]
    print (myList)
    valueToSearch = int(input("Enter the value to search for: "))

    for n in range(0, len(myList)):
        if valueToSearch == myList[n]:
            print (myList[n], "is in index", n)
        elif (n == len(myList)-1) and (valueToSearch != myList[n]):
            print ("No matches")

当输入为7时,最后一行“No matches”是意外的。

4 个答案:

答案 0 :(得分:1)

如果在列表中找到值,则应停止搜索。

for n in range(0, len(myList)):
    if valueToSearch == myList[n]:
        print (myList[n], "is in index", n)
        break
    elif (n == len(myList)-1) and (valueToSearch != myList[n]):
        print ("No matches")

然后,您可以使用python' s for-else子句来改进这一点:

for n in range(0, len(myList)):
    if valueToSearch == myList[n]:
        print (myList[n], "is in index", n)
        break
else:
    print ("No matches")

答案 1 :(得分:1)

想想如果你输入一个不是11的号码会发生什么。让我们说你选择2

达到最终项目。此时,n == len(myList)-1)True,自2 != myList[n]起,该条件也为True,因此"无匹配"打印出来。

您可以使用另一个变量(例如found = False),在找到第一个匹配项后立即设置为True,然后在循环结束时检查该变量。

答案 2 :(得分:1)

你遍历列表,它检查每个值是否等于你查找的值,如果是,它打印一个,否则另一个 - 因此你在列表中的每个元素得到一个输出。 / p>

编辑:重读并看到你需要找到所有,而不仅仅是第一个:

def c7():
    myList = [7, 10, 94, 2, 54, 2, 19, 4, 11]
    print (myList)
    valueToSearch = int(input("Enter the value to search for: "))

    foundOne = False # none found so far
    for idx,value in enumerate(myList): # enumerate gives you index + value of each elem
        if value == valueToSearch:
            print (valueToSearch, "is in index", idx)    
            foundOne = True  # found (at least) one

    if not foundOne: 
        print ("No matches")

如果您只需要获取第一个,只需在列表中获取index of the element并捕获错误(如果不在其中)。

适合蟒蛇ask forgiveness not permission

def c7findFirst():
    myList = [7, 10, 94, 2, 54, 2, 19, 4, 11]
    print (myList)
    valueToSearch = int(input("Enter the value to search for: "))
    try:
        idx = myList.index(valueToSearch)
        print (valueToSearch, "is in index", idx)
    except ValueError: # capture the error if thing is not in list
        print ("No matches")

答案 3 :(得分:0)

试试这个:

def c7():
    myList = [7, 10, 94, 2, 54, 2, 19, 4, 11]
    print (myList)
    valueToSearch = int(input("Enter the value to search for: "))

    for n in range(0, len(myList)):
        if valueToSearch == myList[n]:
            print (myList[n], "is in index", n)
        elif (n == len(myList)-1) and (valueToSearch not in myList):
            print ("%s is not found in list"%valueToSearch)