【问题标题】:How to find the index of two similar numbers in an array? [duplicate]如何在数组中找到两个相似数字的索引? [复制]
【发布时间】:2019-08-08 14:43:53
【问题描述】:

这是我的程序,

item_no = []
max_no = 0
for i in range(5):
    input_no = int(input("Enter an item number: "))
    item_no.append(input_no)
for i in item_no:
    if no > max_no:
       max_no = no
high = item_no.index(max_no)
print (item_no[high])

示例输入:5, 6, 7, 8, 8

示例输出:8

如何更改我的程序以在数组中输出相同的最高数字以及如何在 (item_no) 中找到结果的索引?

预期输出:8, 8

item_no 中结果的预期索引:3, 4

【问题讨论】:

  • 让我们明确一点:您想在一个数组中找到所有最高的数字,将它们放入另一个数组中,打印它们并打印它们的索引?

标签: python arrays python-3.x python-2.7


【解决方案1】:

我会使用max() 来查找最大值。

item_no = []
for i in range(5):
    input_no = int(input("Enter an item number: "))
    item_no.append(input_no)

m = max(item_no)
max_values = [i for i in item_no if i == m]
max_values_indexes = [i for i, j in enumerate(item_no) if j == m]

print(max_values)
print(max_values_indexes)

使用5, 6, 7, 8, 8 作为输入的输出:

[8, 8]
[3, 4]

【讨论】:

    【解决方案2】:

    只需使用过滤器功能来查找所有最大元素,而不是为索引创建一个新列表。

    items = []
    for i in range(5):
        no = int(input("Enter an item number: "))
        items.append(no)
    
    max_item = max(items)
    highest = list(filter(lambda x: x==max_item, items))
    index = [pos for pos, no in enumerate(items) if no == highest[0]]
    print (highest)
    print (index)
    

    输入5、6、7、8、8,你会得到

    [8, 8]
    [3, 4]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-13
      • 2016-03-08
      • 2012-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多