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

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

ได้ลิสต์ที่สมาชิกเป็นสตริงตัวเลข (เช่น '21, 3') ต้องการแปลงเป็นลิสต์ของ tuples

ใช้ map และ eval

ใช้ eval() แปลงสตริงเป็น tuple (ต้องระวังความปลอดภัย)

ตัวอย่าง

listA = ['21, 3', '13, 4', '15, 7']
print("Given list : \n", listA)
res = list(map(eval, listA))
print("List of tuples: \n", res)

ผลลัพธ์

Given list : ['21, 3', '13, 4', '15, 7']
List of tuples: [(21, 3), (13, 4), (15, 7)]

ใช้ map และ split

split(',') แล้ว map(int, ...) แล้ว tuple()

ตัวอย่าง

listA = ['21, 3', '13, 4', '15, 7']
print("Given list : \n", listA)
res = [tuple(map(int, sub.split(', '))) for sub in listA]
print("List of tuples: \n", res)

ผลลัพธ์

Given list : ['21, 3', '13, 4', '15, 7']
List of tuples: [(21, 3), (13, 4), (15, 7)]