【问题标题】:Python3 Error: TypeError: list indices must be integers or slices, not listPython3 错误:TypeError:列表索引必须是整数或切片,而不是列表
【发布时间】:2017-02-22 04:35:15
【问题描述】:
def index_of_smallest(list_nums):
   i = []
   if len(list_nums) == 0:
      return -1
   for i in range(len(list_nums[i] - 1)):
      if i[i] < i[i+1]:
         smallest = i[i]
   return smallest

尝试编写一个通用函数,该函数返回给定列表中最小数字的索引,或者如果列表为空则返回 -1,但我收到一条错误消息:TypeError: list indices must be integers or slices, not列表

我知道有更简单的方法,包括使用 min 方法,但我想使用 for 循环方法来实现这一点
任何指导都会有所帮助

【问题讨论】:

    标签: list python-3.x for-loop


    【解决方案1】:

    更简单的解决方案是使用list 对象的.index() 方法

    def index_of_smallest(list_nums):
        if not(list_nums):
            return -1
        else:
            return list_nums.index(min(list_nums))
    

    用法:

    >> index_of_smallest( [1,2,3,0,5,9] )
       # 3
    
    >> index_of_smallest( [] )
       # -1
    

    其他说明

    您的错误是由于名称空间管理不善造成的。一般来说,你应该避免使用非描述性变量,例如i,因为它们不利于我们理解代码,而且很容易被误用。

    ...range(len(list_nums[i]... 中,您正在索引列表,list_nums 和另一个list,这提高了TypeError。不知道你想在那里做什么对不起。

    在下面,您使用i[i],如果它有效,那么它会非常令人困惑。尽管如此,对迭代器使用单字符变量是很常见的,但仅限于那些范围仅限于非常狭窄的for 循环或列表理解的人。

    this discussion

    【讨论】:

      【解决方案2】:

      一个更简单的解决方案可能是:

      def index_of_smallest(list_nums):
          if(list_nums):
              return list_nums.index(min(list_nums))
      else:
          return -1
      

      做什么:如果列表为空则返回-1(else部分),否则它将在给定列表中找到最小值(min( list_nums)) 然后找到列表中最小元素的索引(list_nums.index(min(list_nums)))

      【讨论】:

      • 1. if 不需要括号。 2. 您可以将您的代码缩短为return int(bool(list_nums)) and list_nums.index(min(list_nums)),然后您可以查找它的作用。 3. 我更喜欢from operator import itemgetter; print(min(enumerate([1, 2, 3]), key=itemgetter(1))[0]),它实际上是numpy 的argmin 函数。真诚的,你曾经向你“炫耀”过你弱蟒技术的 PESIT 学弟。哦,你的缩进是错误的。我对你的回答投了反对票,因为它会引发 SyntaxError。
      猜你喜欢
      • 2019-11-17
      • 2017-11-08
      • 2018-10-13
      • 1970-01-01
      • 2016-09-16
      • 1970-01-01
      • 1970-01-01
      • 2019-07-04
      相关资源
      最近更新 更多