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

สร้าง List of Tuples: ตัวแรกคือตัวเลข ตัวที่สองคือกำลังสอง ใน Python

ใช้ List Comprehension สร้าง Tuple คู่ (ตัวเลข, กำลังสอง) จาก List ตัวเลข

ตัวอย่างโค้ด

my_list = [23, 42, 67, 89, 11, 32]
print("The list is ")
print(my_list)
print("The resultant tuple is :")
my_result = [(val, pow(val, 2)) for val in my_list]
print(my_result)

ผลลัพธ์

The list is [23, 42, 67, 89, 11, 32]
The resultant tuple is : [(23, 529), (42, 1764), (67, 4489), (89, 7921), (11, 121), (32, 1024)]

คำอธิบาย

  • กำหนด List ตัวเลข
  • ใช้ List Comprehension: [(val, pow(val, 2)) for val in my_list]
  • pow(val, 2) คำนวณกำลังสอง
  • ผลลัพธ์เป็น List of Tuples