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

Python - ผลรวมคอลัมน์ของ Tuple

Python มีไลบรารีและฟังก์ชันต่างๆ มากมาย ทำให้ได้รับความนิยมสำหรับการวิเคราะห์ข้อมูล เราอาจมีความต้องการที่จะรวมค่าในคอลัมน์เดียวสำหรับกลุ่มของ Tuple สำหรับการวิเคราะห์ของเรา ดังนั้นในโปรแกรมนี้ เราจะบวกค่าทั้งหมดที่อยู่ในตำแหน่งหรือคอลัมน์เดียวกันในชุดของ Tuple

สามารถทำได้ด้วยวิธีต่อไปนี้

ใช้ For Loop และ Zip

ใช้ for loop วนลูปผ่านแต่ละรายการและใช้ฟังก์ชัน zip เพื่อรวบรวมค่าจากแต่ละคอลัมน์ แล้วใช้ฟังก์ชัน sum และสุดท้ายได้ผลลัพธ์เป็น Tuple ใหม่

ตัวอย่าง

data = [[(3, 92), (21, 4), (15, 6)],[(25, 62), (12, 7), (15, 7)]]
print("The list of tuples: " + str(data))
# ใช้ list comprehension + zip()
result = [tuple(sum(m) for m in zip(*n)) for n in zip(*data)]
print(" Column summation of tuples: " + str(result))

เอาต์พุต

การรันโค้ดข้างต้นให้ผลลัพธ์ดังนี้:

The list of tuples: [[(3, 92), (21, 4), (15, 6)], [(25, 62), (12, 7), (15, 7)]]
Column summation of tuples: [(28, 154), (33, 11), (30, 13)]

ใช้ Map และ Zip

เราสามารถทำผลลัพธ์เดียวกันได้โดยไม่ใช้ for loop และใช้ map function แทน

ตัวอย่าง

data = [[(3, 92), (21, 4), (15, 6)],[(25, 62), (12, 7), (15, 7)]]
print("The list of tuple values: " + str(data))
# ใช้ zip() + map()
result = [tuple(map(sum, zip(*n))) for n in zip(*data)]
print(" Column summation of tuples: " + str(result))

เอาต์พุต

การรันโค้ดข้างต้นให้ผลลัพธ์ดังนี้:

The list of tuple values: [[(3, 92), (21, 4), (15, 6)], [(25, 62), (12, 7), (15, 7)]]
Column summation of tuples: [(28, 154), (33, 11), (30, 13)]