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

Python – แปลงลิสต์สตริงที่มีตัวคั่นเป็นลิสต์ของ Tuple

เมื่อต้องการแปลงลิสต์ของสตริงที่มีตัวคั่น (delimiter) เป็นลิสต์ของ tuple ตัวเลข สามารถใช้ list comprehension, tuple() และ split() ได้

ตัวอย่าง

my_list = ["21$12", "33$24$48$69", "14$10$44"]
print("The list is :")
print(my_list)
key = "$"
print("The key is :")
print(key)
my_result = [tuple(int(element) for element in sub.split(key)) for sub in my_list]
print("The result is :")
print(my_result)

ผลลัพธ์

The list is : ['21$12', '33$24$48$69', '14$10$44']
The key is : $
The result is : [(21, 12), (33, 24, 48, 69), (14, 10, 44)]

คำอธิบาย

  • กำหนดลิสต์สตริงที่คั่นด้วย $ และตัวคั่น key

  • ใช้ list comprehension วนลูปแต่ละสตริง (sub) ใช้ split(key) แยกส่วน

  • แปลงแต่ละส่วนเป็น int แล้วสร้าง tuple

  • แสดงผลลัพธ์ลิสต์ของ tuple ตัวเลข