【问题标题】:Python list iteration with for loop带有for循环的Python列表迭代
【发布时间】:2012-11-12 23:20:48
【问题描述】:

我正在尝试输入数字,我希望我的函数返回最小的数字。

但是,我的代码似乎提前停止执行:只要输入中的一个数字小于另一个。

a = input("")
smallest = 0
a = a.split(" ")
numbers = a

def smallestindex(numbers):
    for i in range(len(numbers)):
        b = int(numbers[i])
        smallest = int(numbers[0])
        print(b)
        if b < smallest:
            smallest = b
            return smallest

print (smallestindex(numbers))

【问题讨论】:

  • l = [int(i) for i in numbers]; print(l.index(min(l))) :-P

标签: python python-3.x


【解决方案1】:

这是一个缩进问题。目前,只要if b &lt; smallest 块运行,您的return 语句就会发生。这可能不是你的本意。您需要取消缩进,使其与 for 语句处于同一级别,以便它在循环结束后运行,而不是在中间运行。

您还需要将初始化smallest 的行移到函数的顶部,而不是让它在循环的每个循环中发生。应该是这样的:

def smallestindex(numbers):
    smallest = int(numbers[0])    # moved this line up
    for i in range(len(numbers)):
        b = int(numbers[i])
        print(b)
        if b < smallest:
            smallest = b
    return smallest   # unindented this line

还值得注意的是,您的循环可能会稍有不同。您可以直接使用for b in numbers 循环遍历列表项,而不是循环遍历列表的索引(使用range(len(numbers)))。

【讨论】:

    【解决方案2】:

    您有一个缩进错误:您在for 循环内返回smallest,因此在满足if 条件的循环的第一次迭代中执行停止。循环完成后,您需要返回结果。此外,您每次通过循环都重置smallest,因此您的if 块不会按照您的意图进行。这是一个固定版本:

    def smallestindex(numbers):
        smallest = int(numbers[0])
        for i in range(len(numbers)):
            b = int(numbers[i])
            print(b)
            if b < smallest:
                smallest = b
        return smallest
    

    【讨论】:

      【解决方案3】:

      如果您希望返回函数名称所暗示的最小数字的索引,则需要将代码更改为类似的内容

      def smallestindex(numbers):
          numbers = [int(x) for x in numbers] # convert numbers to list of ints
          smallest_idx = 0
          smallest = numbers[0]
          for i, b  in enumerate(numbers):
              if b < smallest:
                  smallest_idx = i
                  smallest = b
          return smallest_idx
      

      【讨论】:

        猜你喜欢
        • 2013-01-16
        • 2016-09-04
        • 2012-06-27
        • 2023-03-05
        • 1970-01-01
        • 1970-01-01
        • 2010-11-20
        • 1970-01-01
        • 2016-01-18
        相关资源
        最近更新 更多