Python List and Tuple
ข้อมูลประเภท List และ Tuple ใน Python จะเทียบเท่ากับ Array ในภาษาอื่น ๆ
โดย List/Tuple จะสามารถเก็บตัวแปรได้หลายชนิด
การสร้าง list การสร้าง Tuple
my_favorite_fruits = ["mango", "papaya", "guava", "apple"] tp_data = ("apple", "banana", "cherry")
การเข้าถึงข้อมูล
my_favorite_fruits = ["mango", "papaya", "guava", "apple"]
my_favorite_fruits[0]
my_favorite_fruits[2]
Python List and Tuple
- ข้อมูลประเภท List จะ มีการเรียงลำดับ, แก้ไขได้ และมีสมาชิกซ้ำได้ (ordered, changeable, and allow duplicate)
- ข้อมูลประเภท Tuple เหมือน List แต่แก้ไขไม่ได้
การสร้าง list
list_data = [ ] 🡺 list ว่าง
my_favorite_fruits = ["mango", "papaya", "guava", "apple"]
hello_list = list("hello world") 🡺 ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd’]
num1_list = list(range(10)) 🡺 [0,1,2,3,4,5,6,7,8,9]
num2_list = list(range(5,10)) 🡺 [5,6,7,8,9]
Python List and Tuple
จำนวนข้อมูลใน List 🡺 len(my_favorite_fruits)
การเป็นสมาชิกของ List 🡺 "mango" in my_favorite_fruits หรือ "potato" in my_favorite_fruits
การเพิ่มข้อมูลเข้า List 🡺 my_favorite_fruits.append("orange")
my_favorite_fruits = my_favorite_fruits + ["durian", "grape"]
my_favorite_fruits.extend(["durian", "grape"])
my_favorite_fruits.insert(1, "orange")
ผลรวมของข้อมูลใน list 🡺 sum(num1_list)
การเรียงข้อมูลใน list 🡺 sorted(num1_list), num1_list.sorted()
การลบข้อมูลออกจาก list 🡺 my_favorite_fruits.remove(" mango ")
fr1 = my_favorite_fruits.pop() หรือ fr2 = my_favorite_fruits.pop(2)
del(my_favorite_fruits[2])
my_favorite_fruits.clear()
Python List and Tuple
1. จงเขียนโปรแกรมเพื่อรับตัวเลข 3 ตัวจากคีย์บอร์ดแล้วนำไปใส่ใน list สั่งเรียง / แสดงผลตัวเลขที่มีค่ามากที่สุด -> max(my_list)
2. โปรแกรมให้คะแนนยิมนาสติก โดยจะมีคะแนนจากกรรมการ 5 คน แล้วตัดผู้ที่ให้คะแนนสูงสุด / ต่ำสุดออก แล้วนำคะแนนของ 3 คนกลางมาเฉลี่ย โดยให้มีการแสดงผลดังนี้
Judge 1 score : 7.5
Judge 2 score : 8.2
Judge 3 score : 9.1
Judge 4 score : 7.8
Judge 5 score : 8.3
Score are average of [7.8, 8.2, 8.3] is 8.1
Python List and Tuple
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
for x in "banana":
print(x)
Python List and Tuple
Input Number : 586
Five Eight Six
ห้าร้อยแปดสิบหก
Logic Training : https://studio.code.org/s/20-hour
Python List and Tuple
4. ให้เขียนโปรแกรมเพื่อรับข้อมูลตัวเลขจำนวนเต็ม 6 จำนวนจากคีย์บอร์ดแล้วแสดงแยกจำนวนเลขคู่ เลขคี่ แล้วแสดงผล พร้อมทั้งหาผลรวมของทั้ง 2 ส่วน
Input number 1 : 5
Input number 2 : 6
…
Input number 5 : 12
Input number 6 : 15
Odd Data = [5, …, 15] Sum odd is 27
Even Data = [6, …,12] Sum even is 26
การบ้าน Print Pyramid
ให้เขียนโปรแกรมเพื่อรับค่าตัวเลขแล้ว Print Pyramid ตามตัวอย่าง
Input number : 5
A
C
B
E
D
F
G
H
I