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

เพิ่มองค์ประกอบรายการกับหลายรายการตามดัชนีใน Python

รายการสามารถซ้อนกันได้ หมายความว่าเรามีรายการย่อยเป็นองค์ประกอบภายในรายการใหญ่กว่า ในบทความนี้เราแก้ปัญหาการเพิ่มองค์ประกอบของรายการธรรมดาเข้ากับองค์ประกอบของรายการซ้อน หากความยาวของรายการต่างกัน ความยาวของรายการที่สั้นกว่าจะกลายเป็นความยาวสูงสุดของรายการผลลัพธ์

ด้านล่างเป็นวิธีต่างๆ เพื่อทำสิ่งนี้

ใช้ลูป for

ในวิธีนี้ เราใช้ความยาวของรายการที่สั้นกว่าและวนลูปผ่านองค์ประกอบของรายการนี้เพิ่มเข้ากับองค์ประกอบของรายการที่ใหญ่กว่า ที่นี่เราใช้ฟังก์ชัน append เพื่อเพิ่มแต่ละองค์ประกอบเข้าไปในรายการผลลัพธ์

ตัวอย่าง

simple_list = [25, 35, 45, 55, 65]
nested_list = [[5,10], [10], [5,15], [25], [5,10,15], [5,6]]
result_list = []
for n in range(len(simple_list)):
    var = []
    for m in nested_list[n]:
        var.append(m + simple_list[n])
    result_list.append(var)
print("The first list :", simple_list)
print("The nested list :", nested_list)
print("Result :", result_list)

ผลลัพธ์

การรันโค้ดข้างต้นจะได้ผลดังนี้ −

The first list : [25, 35, 45, 55, 65]
The nested list : [[5, 10], [10], [5, 15], [25], [5, 10, 15], [5, 6]]
Result : [[30, 35], [45], [50, 60], [80], [70, 75, 80]]

ใช้ enumerate()

ฟังก์ชัน enumerate() รับคอลเลกชันเช่นรายการหรือทูเพิลและคืนค่าเป็น enumerate object ในวิธีนี้เราสร้างลูป for ชั้นนอกที่มีฟังก์ชัน enumerate เพื่อรับแต่ละองค์ประกอบของรายการซ้อน และเพิ่มเข้ากับองค์ประกอบที่เกี่ยวข้องในรายการธรรมดาผ่านลูป for ชั้นใน

ตัวอย่าง

simple_list = [25, 35, 45, 55, 65, 25]
nested_list = [[5,10], [10], [5,15], [25], [5,10,15]]
result_list = []
# ใช้ enumerate
result_list = [[val + simple_list[p] for val in q] for p, q in enumerate(nested_list)]
print("The first list :", simple_list)
print("The nested list :", nested_list)
print("Result :", result_list)

ผลลัพธ์

การรันโค้ดข้างต้นจะได้ผลดังนี้ −

The first list : [25, 35, 45, 55, 65, 25]
The nested list : [[5, 10], [10], [5, 15], [25], [5, 10, 15]]
Result : [[30, 35], [45], [50, 60], [80], [70, 75, 80]]

ใช้ zip()

ในวิธีนี้เราทำโปรแกรมข้างต้นซ้ำแต่ใช้ zip() แทน enumerate ฟังก์ชัน zip() รับทั้งสองรายการเป็นอินพุต

ตัวอย่าง

simple_list = [25, 35, 45, 55, 65, 25]
nested_list = [[5,10], [10], [5,15], [25], [5,10,15]]
result_list = []
result_list = [[w + u for w in v] for u, v in zip(simple_list, nested_list)]
print("The first list :", simple_list)
print("The nested list :", nested_list)
print("Result :", result_list)

ผลลัพธ์

การรันโค้ดข้างต้นจะได้ผลดังนี้ −

The first list : [25, 35, 45, 55, 65, 25]
The nested list : [[5, 10], [10], [5, 15], [25], [5, 10, 15]]
Result : [[30, 35], [45], [50, 60], [80], [70, 75, 80]]