Python Programming/Lists

จาก Theory Wiki
ไปยังการนำทาง ไปยังการค้นหา

ลิิสต์ (list) เป็นข้อมูลซึ่งแทนลำดับของค่าต่างๆ เหมือน tuple แต่ว่าเราสามารถเปลี่ยนสมาชิกที่ตำแหน่งต่างๆ ของ list ได้ ซึ่งทำให้ลิสต์คล้ายอะเรย์ในภาษา C มากกว่า tuple เราสามารถสร้าง list ได้ด้วยการเขียนลำดับของสมาชิกใน list ภายในวงเล็บก้ามปู

>>> a = [True, "saber", 3.1415927, "archer", "lancer"]
>>> a
[True, 'saber', 3.1415926999999999, 'archer', 'lancer']
>>> b = ['berserker']
>>> b
['berserker']
>>> c = []
>>> c
[]

สังเกตว่าเราสามารถสร้าง list ที่มีสมาชิกตัวเดียว (b) และ list ว่าง (c) ได้โดยไม่ต้องอาศัยไวยากรณ์แบบพิเศษเช่นเดียวกับ tuple

เราสามารถเปลี่ยนสมาชิก ณ ตำแหน่งต่างของ list ได้

>>> a
[False, 'saber', 3.1415926999999999, 'archer', 'lancer']
>>> a[2] = 22/7
>>> a
[False, 'saber', 3, 'archer', 'lancer']

นอกจากนี้เราสามารถเช็คว่าค่าค่าหนึ่งอยู่ใน list, ทำ slicing, ใช้เครื่องหมายบวก, และคูณ list ด้วยจำนวนเต็มได้เหมือนกับ tuple

>>> "saber" in a
True
>>> 3.1415927 in a
False
>>> a[2:5]
[3, 'archer', 'lancer']
>>> a[:-1]
[False, 'saber', 3, 'archer']
>>> a + b
[False, 'saber', 3, 'archer', 'lancer', 'berserker']
>>> b + a
['berserker', False, 'saber', 3, 'archer', 'lancer']
>>> 4*b
['berserker', 'berserker', 'berserker', 'berserker']
>>> 5*c
[]

การประมวลผล list

ไพทอนมีฟังก์ชันสำหรับทำการคำนวณเกี่ยวกับ list ที่สำคัญอยู่สามฟังก์ชัน ได้แก่ map, filter, และ reduce

ฟังก์ชัน map(f, sequence) เรียกฟังก์ชัน f(x) ที่เรากำหนดโดยมี parameter เป็นสมาชิกของ list sequence แล้วสร้าง list ใหม่ซึ่งมีสมาชิกเป็นผลลัพธ์ฟังก์้ชันนั้น

>>> def plusone(x):
...     return x+1
...
>>> map(plusone, [1,2,3,4,5])
[2, 3, 4, 5, 6]
>>> def cube(x):
...     return x**3
...
>>> map(cube, [-2,-1,0,1,2,100])
[-8, -1, 0, 1, 8, 1000000]

ฟังก์ชัน filter(function, sequence) เรียกฟังก์ชัน f(x) ซึ่งคืนค่าเป็นบูลีน โดยมี parameter เป็นสมาชิกของ list sequence แล้วสร้าง list ของสมาชิกทุกตัวที่ฟังก์ชันคืนค่าเป็น True

>>> def divisible_by_3(x):
...     if x % 3 == 0:
...         return True
...     else:
...         return False
...
>>> filter(divisible_by_3, [1,2,3,4,5,6,7,8,9,10,11,12])
[3, 6, 9, 12]
>>>
>>> def is_prime(x):
...     def check_divisible(x, y):
...         if y < 2:
...             return False
...         else:
...             if x % y == 0:
...                 return True
...             else:
...                 return check_divisible(x, y-1)
...     if x < 2:
...       return False
...     else:
...       return not check_divisible(x, x-1)
...
>>> filter(is_prime, [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20])
[2, 3, 5, 7, 11, 13, 17, 19]
หน้าก่อน: Tuples สารบัญ หน้าต่อไป: Loops