Create Tuple from String and List
เมื่อต้องการสร้าง Tuple จาก String และ List สามารถใช้เมธอด tuple() ได้
List เก็บข้อมูลหลายชนิดได้
List สามารถเก็บข้อมูลประเภทต่างๆ ได้ (Integer, Float, String, etc.)
ตัวอย่างโค้ด
my_list_1 = ['Hey', 'there', 'How', 'are', 'you']
my_list_2 = 'Jane'
print("The first list is :")
print(my_list_1)
print("The string is :")
print(my_list_2)
# รวม List กับ String (ใส่ String ใน List) แล้วแปลงเป็น Tuple
my_result = tuple(my_list_1 + [my_list_2])
print("The aggregated tuple is : ")
print(my_result)
ผลลัพธ์
The first list is : ['Hey', 'there', 'How', 'are', 'you']
The string is : Jane
The aggregated tuple is : ('Hey', 'there', 'How', 'are', 'you', 'Jane')
คำอธิบาย
- สร้าง List และแสดงผล
- กำหนด String อีกตัว
- ใช้
my_list_1 + [my_list_2]รวม List กับ List ที่มี String อยู่คนเดียว - แปลงเป็น Tuple ด้วย
tuple() - แสดงผล Tuple ที่รวมแล้ว
วิธีอื่นๆ
# 1. ใช้ * Unpacking (Python 3.5+)
my_result = (*my_list_1, my_list_2)
# ('Hey', 'there', 'How', 'are', 'you', 'Jane')
# 2. ใช้ List extend แล้วแปลง
temp = my_list_1.copy()
temp.append(my_list_2)
my_result = tuple(temp)
# 3. ใช้ itertools.chain
from itertools import chain
my_result = tuple(chain(my_list_1, [my_list_2]))
กรณี String หลายตัว
my_list = ['a', 'b']
strings = ['c', 'd', 'e']
result = tuple(my_list + strings)
print(result) # ('a', 'b', 'c', 'd', 'e')