说清单= [9、8、9、10]。例如,如何找到9的位置?

功能

def find_value(num_list,target):
    target_loc = []  # list to store the location of the target
    condition = True
    while condition == True:
        for target in num_list:
            if target in num_list:
                index = num_list.index(target)
                target_loc.append(index)
                condition = True
        else:
            condition = False    
    return target_loc

主程序:

num_list = keep_positive_numbers()
print()
print("List entered: ",num_list)
print()
target = int(input("Enter target = "))
print()
list = find_value(num_list,target)
print("Target exists at location(s): ",list)

输出

输入一个正整数:9 输入一个正整数:9 输入一个正整数:8 输入一个正整数:0

输入的列表:[9,9,8]

输入目标= 7

目标存在于[0、0、2]个位置

littlejade 回答:说清单= [9、8、9、10]。例如,如何找到9的位置?

您可以使用list comprehensionenumerate

def find_value(num_list,target):
    return [i for i,x in enumerate(num_list) if x == target]

find_value([9,8,9,10],9)
# [0,2]

或者,如果您希望进行显式循环,请在索引上使用for循环:

def find_value(num_list,target):
    target_loc = []  # list to store the location of the target
    for i in range(len(num_list)):  
        if target == num_list[i]:
            target_loc.append(i)
    return target_loc

您必须一个一个地检查索引。 list.index总是返回 first 一个。

本文链接:https://www.f2er.com/3150151.html

大家都在问