ในบทช่วยสอนนี้ เราจะเขียนโปรแกรมที่เพิ่มค่าทั้งหมดด้วยคีย์เดียวกัน แสดงรายการต่างๆ มาดูตัวอย่างให้เข้าใจกันชัดๆ
อินพุต
list_one = [('a', 2), ('b', 3), ('c', 5)]
list_two = [('c', 7), ('a', 4), ('b', 2)] ผลลัพธ์
[('a', 6), ('b', 5), ('c', 12)] ทำตามขั้นตอนที่กำหนดเพื่อแก้ปัญหา
- เริ่มต้นรายการ
- แปลงรายการแรกเป็นพจนานุกรมโดยใช้ dict และเก็บไว้ในตัวแปร
- วนซ้ำในรายการที่สองและเพิ่มค่าที่เกี่ยวข้องให้กับคีย์ที่มีอยู่ในพจนานุกรม
- พิมพ์ผลลัพธ์
ตัวอย่าง
# initializing the lists
list_one = [('a', 2), ('b', 3), ('c', 5)]
list_two = [('c', 7), ('a', 4), ('b', 2)]
# convering list_one to dict
result = dict(list_one)
# iterating over the second list
for tup in list_two:
# checking for the key in dict
if tup[0] in result:
result[tup[0]] = result.get(tup[0]) + tup[1]
# printing the result as list of tuples
print(list(result.items())) ผลลัพธ์
หากคุณเรียกใช้โค้ดด้านบน คุณจะได้ผลลัพธ์ดังต่อไปนี้
[('a', 6), ('b', 5), ('c', 12)] เราสามารถแก้ปัญหาข้างต้นได้โดยไม่ต้องทำซ้ำรายการใดๆ โดยใช้ Counter fromcollections . มาดูกันเลย
ตัวอย่าง
# importing the Counter
from collections import Counter
# initializing the lists
list_one = [('a', 2), ('b', 3), ('c', 5)]
list_two = [('c', 7), ('a', 4), ('b', 2)]
# getting the result
result = Counter(dict(list_one)) + Counter(dict())
# printing the result as list of tuples
print(list(result.items())) ผลลัพธ์
หากคุณเรียกใช้โค้ดด้านบน คุณจะได้ผลลัพธ์ดังต่อไปนี้
[('a', 6), ('b', 5), ('c', 12)] บทสรุป
หากคุณมีข้อสงสัยเกี่ยวกับบทแนะนำ โปรดระบุในส่วนความคิดเห็น