скажем список = [9, 8, 9, 10]. Как я могу найти местоположение (я) 9, например? - PullRequest
0 голосов
/ 06 ноября 2019

Функция

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]

1 Ответ

2 голосов
/ 06 ноября 2019

Вы можете использовать список понимания и 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 для overиндексы:

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 всегда возвращает первый один.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...