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

โปรแกรม Python หาค่า y กำลังสาม (Cube) ของทุกสมาชิกในลิสต์


ตัวอย่าง

โค้ดด้านล่างคำนวณกำลังสามของแต่ละสมาชิกในลิสต์โดยใช้ loop และ append

my_list = [45, 31, 22, 48, 59, 99, 0]
print("The list is :")
print(my_list)
my_result = []
for i in my_list:
    my_result.append(i * i * i)
print("The resultant list is :")
print(my_result)

ผลลัพธ์

The list is : [45, 31, 22, 48, 59, 99, 0]
The resultant list is : [91125, 29791, 10648, 110592, 205379, 970299, 0]

คำอธิบาย

  • กำหนดลิสต์และแสดงผล

  • สร้างลิสต์ว่าง

  • วนลูปแต่ละค่า คำนวณ i*i*i append เข้า result

  • แสดงผลลัพธ์