【问题标题】:How do you find the location of an item in a list without using the "index" function?如何在不使用“索引”功能的情况下找到列表中项目的位置?
【发布时间】:2014-12-12 03:36:08
【问题描述】:

我是编程初学者,我正在尝试创建一个程序,在不使用“max”函数的情况下,在 1000 个随机数的列表中找到最大的数字,然后在列表中找到最大的数字位置,不使用“索引”功能(我将数字设置为 0-10,以便确保程序正常运行)。到目前为止,我的程序可以正常工作。有时,它会显示位置,当它显示时,它会显示错误的位置,而其他时候,它会显示一个错误,指出索引超出范围。有人可以帮忙吗?

import random
num_list = []
for num in range(10):
    num_list.append(random.randrange(0,11))
max_num = -1
for num in num_list:
    if num > max_num:
        max_num = num
        location=num_list[max_num]
print "The computer entered: " + str(num_list) 
print "The largest number in this list is: " + str(max_num) + " The location is: " + str(location)

【问题讨论】:

    标签: python for-loop random indexing max


    【解决方案1】:

    编辑以反映来自@JonClements 的反馈

    max_num = -1
    for (i, num) in enumerate(num_list):
      if num > max_num:
        location = i
        max_num = num
    

    【讨论】:

    • 你最好在这里使用enumerate 而不是range(...)
    【解决方案2】:

    问题是num_list[max_num] 作为索引访问最大值.. 例如在[1 10 2] 中,您要求的是列表中的第 10 个值!尝试更改为:

    import random
    num_list = []
    n = 1000
    for num in range(n):
        num_list.append(random.randrange(0,n))
    max_num = -1
    i = 0
    for num in num_list:
        if num > max_num:
            max_num = num
            location=i
        i += 1
    print "The computer entered: " + str(num_list) 
    print "The largest number in this list is: " + str(max_num) + " The location is: " +  str(location)
    

    【讨论】:

      【解决方案3】:

      使用enumerate:

      import random
      num_list = []
      for num in range(10):
          num_list.append(random.randrange(0,11))
      max_num = -1
      location = -1
      for index, num in enumerate(num_list): # <-- Use enumerate
          if num > max_num:
              max_num = num
              location=index # <-- Store the index for the largest number we found until now
      
      print "The computer entered: " + str(num_list) 
      print "The largest number in this list is: " + str(max_num) + " The location is: " + str(location)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-08-21
        • 2018-09-27
        • 1970-01-01
        • 1970-01-01
        • 2022-01-21
        • 1970-01-01
        • 2019-09-08
        • 1970-01-01
        相关资源
        最近更新 更多