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

การผูกค่าเดียวกับทุกสมาชิกในลิสต์ Python

บางครั้งเราต้องการผูกค่าเดียวกันกับทุกสมาชิกในลิสต์ ตัวอย่างเช่น มีลิสต์ชื่อวัน และต้องการเติมคำว่า "day" ต่อท้ายทุกชื่อวัน สามารถทำได้หลายวิธี

วิธีที่ 1: ใช้ itertools.repeat

ใช้ฟังก์ชัน repeat จากโมดูล itertools เพื่อสร้าง iterator ที่คืนค่าเดิมซ้ำๆ แล้วนำไป 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 values:\n", res)

ผลลัพธ์

The Given list: ['Sun', 'Mon', 'Tues']
Value to be attached: day
List with associated values: [('Sun', 'day'), ('Mon', 'day'), ('Tues', 'day')]

วิธีที่ 2: ใช้ lambda และ map

ใช้ lambda สร้างฟังก์ชันไม่มีชื่อที่จับคู่แต่ละสมาชิกกับค่าที่ต้องการ แล้วใช้ map ให้ทำงานกับทุกสมาชิกในลิสต์

ตัวอย่าง

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 values:\n", res)

ผลลัพธ์

The Given list: ['Sun', 'Mon', 'Tues']
Value to be attached: day
List with associated values: [('Sun', 'day'), ('Mon', 'day'), ('Tues', 'day')]

ทั้งสองวิธีให้ผลลัพธ์เป็นลิสต์ของ tuple ที่แต่ละ tuple ประกอบด้วย (สมาชิกเดิม, ค่าที่ผูก) วิธีที่ 2 เข้าใจง่ายกว่าและไม่ต้อง import เพิ่ม