เราอาจจำเป็นต้องเชื่อมโยงค่าที่กำหนดกับแต่ละองค์ประกอบของรายการ ตัวอย่างเช่น มีชื่อของวันและเราต้องการที่จะแนบคำว่าวันเป็นคำต่อท้ายในนั้น สถานการณ์ดังกล่าวสามารถจัดการได้ด้วยวิธีต่อไปนี้
ด้วย itertools.repeat
เราสามารถใช้วิธีทำซ้ำจากโมดูล itertools เพื่อให้ใช้ค่าเดิมซ้ำแล้วซ้ำอีกเมื่อจับคู่กับค่าจากรายการที่กำหนดโดยใช้ฟังก์ชัน zip
ตัวอย่าง
from itertools import repeat
listA = ['Sun','Mon','Tues']
val = 'day'
print ("The Given list : ",listA)
print ("Value to be attached : ",val)
# With zip() and itertools.repeat()
res = list(zip(listA, repeat(val)))
print ("List with associated vlaues:\n" ,res) ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
The Given list : ['Sun', 'Mon', 'Tues']
Value to be attached : day
List with associated vlaues:
[('Sun', 'day'), ('Mon', 'day'), ('Tues', 'day')] พร้อมแลมบ์ดาและแผนที่
เมธอดแลมบ์ดาสร้างและวนซ้ำองค์ประกอบรายการและเริ่มจับคู่ ฟังก์ชันแผนที่ช่วยให้แน่ใจว่าองค์ประกอบทั้งหมดที่อยู่ในรายการถูกครอบคลุมโดยการจับคู่องค์ประกอบในรายการกับค่าที่กำหนด
ตัวอย่าง
listA = ['Sun','Mon','Tues']
val = 'day'
print ("The Given list : ",listA)
print ("Value to be attached : ",val)
# With map and lambda
res = list(map(lambda i: (i, val), listA))
print ("List with associated vlaues:\n" ,res) ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
The Given list : ['Sun', 'Mon', 'Tues']
Value to be attached : day
List with associated vlaues:
[('Sun', 'day'), ('Mon', 'day'), ('Tues', 'day')]