简体   繁体   English

数组中的最小数 python

[英]Smallest number in an array python

Trying to find the smallest number in an array that the user inputs.试图在用户输入的数组中找到最小的数字。 Here's what I have:这是我所拥有的:

def main():
   numbers = eval(input("Give me an array of numbers: "))
   smallest = numbers[0]
   for i in range(0,len(numbers),1):
      if (numbers[i] < smallest):
         smallest = numbers[i]
         print("The smallest number is: ", smallest)
main()

The result I'm looking for is to be:我正在寻找的结果是:

Give me an array of numbers: [11, 5, 3, 51]
The smallest number is 3

Instead, this is what I am getting:相反,这就是我得到的:

Give me an array of numbers: [11, 5, 3, 51]
The smallest number is:  5
The smallest number is:  3

Can anyone help me figure out where I am messing up?谁能帮我弄清楚我在哪里搞砸了? Thanks in advance.提前致谢。

您可以只使用min()

print("The smallest number is: ", min(numbers))

You have to print the output only once after the loop finishes. 循环完成后,您只需打印一次输出。

def main():
   numbers = eval(input("Give me an array of numbers: "))
   smallest = numbers[0]
   for i in range(0,len(numbers),1):
      if (numbers[i] < smallest):
         smallest = numbers[i]
   print("The smallest number is: ", smallest)
main()

Or use min() as Christian suggested. 或使用Christian建议的min()

Lets assume an array as arr让我们假设一个数组为 arr

Method 1: First sorting an array in ascending order & then printing the element of 0 index方法一:先对数组进行升序排序,然后打印索引为0的元素

arr = [2,5,1,3,0]
arr.sort()
print(arr[0])

Method 2: Using For loop until we get the smallest number then min方法2:使用For循环,直到我们得到最小的数字然后min

arr = [2,5,1,3,0]
min = arr[0]
for i in range (len(arr)):
    if arr[i] < min:
        min = arr[i]
print(min)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM