【问题标题】:say list = [9, 8, 9, 10]. How do I find the location(s) of the 9s for example?说列表 = [9, 8, 9, 10]。例如,我如何找到 9 的位置?
【发布时间】:2019-11-06 17:19:46
【问题描述】:

功能

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]

【问题讨论】:

  • [0, 0, 2]7[9, 9, 8]中的位置如何?
  • m8 idek 我是编程新手。它在列表 [9, 9, 8] 中显示了 9 和 8 的位置,但是它只考虑了 9 的第一个位置。我也刚刚意识到目标是 7,但它给出了元素的位置列表。
  • 您的预期输出一般是什么——对于[9,8,9,10]9[0, 2] 有机会吗?

标签: python python-3.x list iteration


【解决方案1】:

您可以使用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 总是返回第一个

【讨论】:

  • 哦该死的好的,谢谢,但还有其他方法吗,因为我认为我们的教授没有教过我们,所以我不确定我是否可以使用这种方法。如果没有,那就不用担心了。再次非常感谢。
猜你喜欢
  • 2021-01-21
  • 2017-11-11
  • 2013-11-04
  • 1970-01-01
  • 2021-06-29
  • 2022-08-11
  • 2013-12-23
  • 2020-11-27
  • 1970-01-01
相关资源
最近更新 更多