มารู้จักตัวแปรชนิด tuple ในภาษา python

ตอบกระทู้

รูปแสดงอารมณ์
:icon_plusone: :like: :plusone: :gfb: :-D :) :( :-o 8O :? 8) :lol: :x :P :oops: :cry: :evil: :twisted: :roll: :wink: :!: :?: :idea: :arrow: :| :mrgreen: :angry: :baa: :biggrin:
รูปแสดงอารมณ์อื่นๆ

BBCode เปิด
[img] เปิด
[url] เปิด
[Smile icon] เปิด

กระทู้แนะนำ
   

มุมมองที่ขยายได้ กระทู้แนะนำ: มารู้จักตัวแปรชนิด tuple ในภาษา python

มารู้จักตัวแปรชนิด tuple ในภาษา python

โดย jirawoot » 24/06/2019 5:50 pm

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

โค้ด: เลือกทั้งหมด

name=('prthon','mindphp','PHP','test',)
num=(1,2,3,4,5,6,7,8,9)
a=('prthon','mindphp','test',1,2,3)
การแสดงผลตัวแปรชนิด tuple
ในการแสดงผลของตัวแปรชนิด tuple จะใช้คำสั่ง print ในการเเสดงผลของข้อมูล

โค้ด: เลือกทั้งหมด

name=('prthon','mindphp','PHP','test',)
num=(1,2,3,4,5,6,7,8,9)
a=('prthon','mindphp','test',1,2,3)
print(name)
print(num)
print(a)
จะได้ผลลัพธ์
Selection_025.png
Selection_025.png (10.23 KiB) Viewed 2759 times
ในการแสดงผลแบบระบุ index ก็เช่นเดียวกับตัวแปรชนิด list เลย โดยจะมี ชื่อตัวแปรแล้วตามด้วย index ครับ
ดังตัวอย่าง

โค้ด: เลือกทั้งหมด

name=('prthon','mindphp','PHP','test',)
num=(1,2,3,4,5,6,7,8,9)
a=('prthon','mindphp','test',1,2,3)

print('name[3]=',name[3])
print('num[2]=',num[2])
จะได้ผลลัพธ์
Selection_026.png
Selection_026.png (7.72 KiB) Viewed 2759 times
ตัวแปรชนิด tuple จะไม่สามารถลบได้นะครับ
ดังตัวอย่าง

โค้ด: เลือกทั้งหมด

name=('prthon','mindphp','PHP','test',)
num=(1,2,3,4,5,6,7,8,9)
a=('prthon','mindphp','test',1,2,3)

del name[0]
จะได้ผลลัพธ์
Selection_027.png
Selection_027.png (13.53 KiB) Viewed 2759 times
ตัวดำเนินการของตัวแปรชนิด tuple มีดังนี้
Selection_028.png
Selection_028.png (16.5 KiB) Viewed 2759 times
จะมีตัวอย่างดังนี้

โค้ด: เลือกทั้งหมด

name=('prthon','mindphp','PHP','test',)
num=(1,2,3,4,5,6,7,8,9)
a=('prthon','mindphp','test',1,2,3)

print(len(name))
print(name+num)
print(name*2)
print(1 in a)

for x in name:
    print(x)
จะได้ผลลัพธ์
Selection_029.png
Selection_029.png (11.8 KiB) Viewed 2759 times

ข้างบน