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

วิธี Index และ Slice Tuple ใน Python

Index หรือ slice tuple ใช้ operator [] บน tuple index บวกดึงจากซ้าย index ลบดึงจากขวา

ตัวอย่าง

my_tuple = ('a', 'b', 'c', 'd')
print(my_tuple[1])
print(my_tuple[-1])

ผลลัพธ์

b
d

ดึงส่วนของ tuple ใช้ slicing [start:stop:step]

ตัวอย่าง

my_tuple = ('a', 'b', 'c', 'd')
print(my_tuple[1:])   # index 1 ถึงสุด
print(my_tuple[:2])   # เริ่มต้นถึง index 2
print(my_tuple[1:3])  # index 1 ถึง 3
print(my_tuple[::2])  # เริ่มต้นถึงสุด step 2

ผลลัพธ์

('b', 'c', 'd')
('a', 'b')
('b', 'c')
('a', 'c')