1-D arrays (lists) · -array 1 (รายการ)
A list holds many values
- A list (the exam calls it an array) stores many values under one name.
- Write the items in square brackets, separated by commas.
- An array normally stores items of the same type.
รายการเก็บหลายค่าได้
- รายการ (list) ซึ่งในการสอบเรียกว่า อาร์เรย์ (array) เก็บหลายค่าภายใต้ชื่อเดียว
- เขียนรายการในวงเล็บเหลี่ยม คั่นด้วยเครื่องหมายลูกน้ำ
- อาร์เรย์โดยทั่วไปจะเก็บรายการที่มี ประเภทเดียวกัน
scores = [40, 55, 72, 90]
print(scores)
Reach an item by its index
- Each item has a position number called its index.
- Python counts from 0, so the first item is
scores[0].
เข้าถึงรายการโดยใช้ดัชนี
- แต่ละรายการมีตำแหน่งหมายเลขที่เรียกว่า ดัชนี (index)
- Python นับจาก 0 ดังนั้นรายการแรกจึงอยู่ที่
scores[0]
scores = [40, 55, 72, 90]
print(scores[0]) # 40
print(scores[2]) # 72
Index and change a list · ดัชนีและการแก้ไขรายการ
Items are numbered from 0; scores[0] is the first item. · รายการมีเลขลำดับเริ่มจาก 0; ⟨scores[0]⟩ เป็นรายการ第一项.
Change an item
- Assign to an index to replace that one item.
เปลี่ยนค่ารายการ
- กำหนดค่าที่ตำแหน่ง (index) เพื่อแทนที่รายการนั้น
scores = [40, 55, 72, 90]
scores[1] = 99
print(scores) # [40, 99, 72, 90]
Length and looping
len(scores)gives how many items there are.- A
forloop visits each item in turn.
ความยาวและการวนลูป
- การใช้
len(scores)จะบอกจำนวนรายการทั้งหมด - การใช้
forloop จะเข้าเยี่ยมแต่ละรายการตามลำดับ
scores = [40, 55, 72, 90]
print(len(scores)) # 4
for s in scores:
print(s)
In the exam: arrays start at 1
- Pseudocode declares an array with a size, and usually counts from 1.
ในการสอบ: อาร์เรย์เริ่มต้นที่ 1
- ปсевโคดประกาศอาร์เรย์ด้วยขนาด และโดยทั่วไปนับจาก 1
DECLARE Scores : ARRAY[1:4] OF INTEGER
Scores[1] ← 40
OUTPUT Scores[1]
Common mistakes
- Index from
0; the last item is at positionlength - 1. - Going past the end gives an index error.
ข้อผิดพลาดที่พบบ่อย
- ใช้ index เริ่มต้นที่
0; รายการสุดท้ายอยู่ที่ตำแหน่งlength - 1 - การเข้าถึงเกินขอบเขตจะเกิดข้อผิดพลาดเรื่อง index
Now you try
- Use an index, or a loop, on each list.
- Press Check answer to test your code.
ลองดูเลย
- ใช้ index หรือลูปเพื่อจัดการกับแต่ละรายการในลิสต์
- กด Check answer เพื่อทดสอบโค้ดของคุณ
The list colours is set for you. Store its second item in a variable called second (remember Python counts from 0). · รายการ colours ถูกกำหนดไว้แล้ว เก็บรายการ ลำดับที่สอง ของมันลงในตัวแปรชื่อ second (จำไว้ว่า Python นับจาก 0)
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Change the first item of the list nums to 99. · เปลี่ยนรายการ ลำดับแรก ของรายการ nums ให้เป็น 99
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Use a loop to add up every number in nums and store the result in total (the answer is 43). · ใช้ลูปเพื่อบวกเลขทุกจำนวนใน nums และเก็บผลลัพธ์ลงใน total (คำตอบคือ 43)
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่