首页 > 解决方案 > 说列表 = [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]

标签: pythonpython-3.xlistiteration

解决方案


您可以使用列表理解enumerate

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总是返回一个。


推荐阅读