寫一個 Python 程序,用一個實際例子找到列表中最小的數字。
Python min 函數返回列表中的最小值。
# Python Program to find Smallest Number in a List
a = [10, 50, 60, 80, 20, 15]
print("The Smallest Element in this List is : ", min(a))
Python 最小列表號輸出
The Smallest Element in this List is : 10
這個 python 程序同上。但是這次,我們允許用戶輸入列表的長度。接下來,我們使用 For Loop 給 Python 列表添加數字。
NumList = []
Number = int(input("Please enter the Total Number of List Elements: "))
for i in range(1, Number + 1):
value = int(input("Please enter the Value of %d Element : " %i))
NumList.append(value)
print("The Smallest Element in this List is : ", min(NumList))
Python 排序函數按照升序對列表元素進行排序。接下來,我們使用索引位置 0 來列印列表中的第一個元素。
a = [100, 50, 60, 80, 20, 15]
a.sort()
print("The Smallest Element in this List is : ", a[0])
Python 最小列表號使用排序函數輸出
The Smallest Element in this List is : 20
這個 Python 列表最小的數字和上面一樣。但是這次,我們允許用戶輸入他們自己的列表項。
NumList = []
Number = int(input("Please enter the Total Number of List Elements: "))
for i in range(1, Number + 1):
value = int(input("Please enter the Value of %d Element : " %i))
NumList.append(value)
NumList.sort()
print("The Smallest Element in this List is : ", NumList[0])
Python 最小列表號輸出
Please enter the Total Number of List Elements: 6
Please enter the Value of 1 Element : 7
Please enter the Value of 2 Element : 9
Please enter the Value of 3 Element : 22
Please enter the Value of 4 Element : 90
Please enter the Value of 5 Element : 5
Please enter the Value of 6 Element : 67
The Smallest Element in this List is : 5
在這個程序中,我們沒有使用任何內置函數,比如 sort,或者 min 函數。
NumList = []
Number = int(input("Please enter the Total Number of List Elements: "))
for i in range(1, Number + 1):
value = int(input("Please enter the Value of %d Element : " %i))
NumList.append(value)
smallest = NumList[0]
for j in range(1, Number):
if(smallest > NumList[j]):
smallest = NumList[j]
position = j
print("The Smallest Element in this List is : ", smallest)
print("The Index position of the Smallest Element is : ", position)
Python 列表輸出中最小的數字
Please enter the Total Number of List Elements: 5
Please enter the Value of 1 Element : 223
Please enter the Value of 2 Element : 43
Please enter the Value of 3 Element : 22
Please enter the Value of 4 Element : 67
Please enter the Value of 5 Element : 54
The Smallest Element in this List is : 22
The Index position of the Smallest Element is : 2
從上面的 Python 程序中查找列表示例中的最小數字,用戶插入的值是
NumList[5] = {223,43,22,67,54 }
minist = NumList[0]= 223
第一次迭代–對於範圍(1,5)中的 1–條件為真
因此,它開始在循環內執行 If 語句,直到條件失敗。
如果 for 循環內的(最小> NumList[j])為真,因為(223 > 43)
最小= NumList[1]
最小= 43
位置= 1
第二次迭代:對於範圍(1,5)中的 2–條件為真
If(最小>NumList[2])=(43>22)–條件為真
最小= NumList[2]
最小= 22
位置= 2T7】
第三次迭代:對於範圍(1,5)中的 3–條件為真
如果(最小>NumList【3】)=(22>67)–條件為假
最小= 22
位置= 2
第四次迭代:對於範圍(1,5)中的 4–條件為真
如果(22>54)–條件為假
最小= 22
位置= 2
第五次迭代:對於範圍(1,5)中的 5–條件為假
因此,它退出循環。
原創文章,作者:RMTYR,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/126811.html