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

รวม tuples ในลิสต์ของ tuples ใน Python

ลิสต์ที่สมาชิกเป็น tuple (list, string) ต้องการจับคู่แต่ละสมาชิกใน list กับ string นั้น

ตัวอย่าง: [([2,8,9],'Mon'), ([7,5,6],'Wed')] → [(2,'Mon'),(8,'Mon'),(9,'Mon'),(7,'Wed'),(5,'Wed'),(6,'Wed')]

ใช้ for loop

[(t1, t2) for i, t2 in Alist for t1 in i]

ตัวอย่าง

Alist = [([2, 8, 9], 'Mon'), ([7, 5, 6], 'Wed')]
print("List of tuples : \n", Alist)
res = [(t1, t2) for i, t2 in Alist for t1 in i]
print("The list tuple combination : \n", res)

ผลลัพธ์

List of tuples : [([2, 8, 9], 'Mon'), ([7, 5, 6], 'Wed')]
The list tuple combination : [(2, 'Mon'), (8, 'Mon'), (9, 'Mon'), (7, 'Wed'), (5, 'Wed'), (6, 'Wed')]

ใช้ itertools.product

product(i, [j]) สร้าง Cartesian product ของ list i กับ [j]

ตัวอย่าง

from itertools import product
Alist = [([2, 8, 9], 'Mon'), ([7, 5, 6], 'Wed')]
print("List of tuples : \n", Alist)
res = [x for i, j in Alist for x in product(i, [j])]
print("The list tuple combination : \n", res)

ผลลัพธ์

List of tuples : [([2, 8, 9], 'Mon'), ([7, 5, 6], 'Wed')]
The list tuple combination : [(2, 'Mon'), (8, 'Mon'), (9, 'Mon'), (7, 'Wed'), (5, 'Wed'), (6, 'Wed')]