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

แปลงลิสต์ของ tuples เป็นลิสต์ของสตริงใน Python

ในการประมวลผลข้อมูล อาจได้ลิสต์ที่สมาชิกเป็น tuples ต้องการแปลงแต่ละ tuple เป็นสตริง

ใช้ join()

join() รวมสมาชิกของ sequence ด้วย separator ที่กำหนด ใช้ list comprehension

ตัวอย่าง

listA = [('M','o','n'), ('d','a','y'), ('7', 'pm')]
print("Given list : \n", listA)
res = [''.join(i) for i in listA]
print("Final list: \n", res)

ผลลัพธ์

Given list : [('M', 'o', 'n'), ('d', 'a', 'y'), ('7', 'pm')]
Final list: ['Mon', 'day', '7pm']

ใช้ map และ join

ใช้ map('',join, listA) แล้ว wrap ด้วย list()

ตัวอย่าง

listA = [('M','o','n'), ('d','a','y'), ('7', 'pm')]
print("Given list : \n", listA)
res = list(map(''.join, listA))
print("Final list: \n", res)

ผลลัพธ์

Given list : [('M', 'o', 'n'), ('d', 'a', 'y'), ('7', 'pm')]
Final list: ['Mon', 'day', '7pm']