Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การใช้ min() และ max() ใน Python


ในบทความนี้ เราจะเรียนรู้เกี่ยวกับฟังก์ชัน min และ max ที่รวมอยู่ใน Python Standard Library มันยอมรับจำนวนพารามิเตอร์ไม่จำกัดตามการใช้งาน

Syntax

max(arg1, arg2, arg3, ...........)

Return Value − ค่าสูงสุดของอาร์กิวเมนต์ทั้งหมด

Errors & Exceptions: Error จะเกิดขึ้นเฉพาะในสถานการณ์ที่อาร์กิวเมนต์ไม่ใช่ประเภทเดียวกัน Error จะเกิดขณะเปรียบเทียบพวกมัน

มาดูว่ามีวิธีไหนบ้างที่เราสามารถนำฟังก์ชัน max() ไปใช้งานได้

ตัวอย่าง

# หาค่าสูงสุดจากชุดอาร์กิวเมนต์ที่ส่งมา
print("Maximum value among the arguments passed is:" + str(max(2, 3, 4, 5, 7, 2, 1, 6)))
# คำสั่งข้างต้นทำงานได้สำหรับตัวอักษรเป็นอาร์กิวเมนต์ด้วย
print("Maximum value among the arguments passed is:" + str(max('m', 'z', 'a', 'b', 'e')))
# มันยอมรับอาร์กิวเมนต์ที่แมปในรูปแบบลิสต์
l = [22, 45, 1, 7, 3, 2, 9]
print("Maximum element of the list is:" + str(max(l)))
# มันยอมรับอาร์กิวเมนต์ที่แมปในรูปแบบทูเพิล
l = (22, 45, 1, 7, 71, 91, 3, 2, 9)
print("Maximum element of the tuple is:" + str(max(l)))

ผลลัพธ์

Maximum value among the arguments passed is:7
Maximum value among the arguments passed is:z
Maximum element of the list is:45
Maximum element of the tuple is:91

ที่นี่ชัดเจนว่าด้วยการใช้ built-in functions เช่น max() เราสามารถได้ค่าสูงสุดในอาร์กิวเมนต์โดยตรงโดยไม่ต้องดำเนินการเปรียบเทียบจริง

เช่นเดียวกัน เราสามารถนำฟังก์ชัน min() ไปใช้งานได้ที่นี่

ตัวอย่าง

# หาค่าน้อยสุดจากชุดอาร์กิวเมนต์ที่ส่งมา
print("Minimum value among the arguments passed is:" + str(min(2, 3, 4, 5, 7, 2, 1, 6)))
# คำสั่งข้างต้นทำงานได้สำหรับตัวอักษรเป็นอาร์กิวเมนต์ด้วย
print("Minimum value among the arguments passed is:" + str(min('m', 'z', 'a', 'b', 'e')))
# มันยอมรับอาร์กิวเมนต์ที่แมปในรูปแบบลิสต์
l = [22, 45, 1, 7, 3, 2, 9]
print("Minimum element of the list is:" + str(min(l)))
# มันยอมรับอาร์กิวเมนต์ที่แมปในรูปแบบทูเพิล
l = (22, 45, 1, 7, 71, 91, 3, 2, 9)
print("Minimum element of the tuple is:" + str(min(l)))

ผลลัพธ์

Minimum value among the arguments passed is:1
Minimum value among the arguments passed is:a
Minimum element of the list is:1
Minimum element of the tuple is:1

ด้วยการใช้ built-in functions เช่น max() และ min() เราสามารถได้ค่าสูงสุดและต่ำสุดที่ตรงกันโดยตรงโดยไม่ต้องนำตรรกะการเปรียบเทียบจริงไปใช้งาน

สรุป

ในบทความนี้ เราได้เรียนรู้การนำ max และ min function ที่รวมอยู่ใน Python Standard Library ไปใช้งาน