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

โปรแกรม Python สลับค่าแรกและค่าสุดท้ายของ List


ภาพรวม

เมื่อต้องการสลับค่าแรกและค่าสุดท้ายของ List ใน Python สามารถนิยามเมธอด ใช้เทคนิคการจัดเรียงง่ายๆ เพื่อสลับค่า

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

def list_swapping(my_list):
    size_of_list = len(my_list)
    temp = my_list[0]
    my_list[0] = my_list[size_of_list - 1]
    my_list[size_of_list - 1] = temp
    return my_list

my_list = [34, 21, 56, 78, 93, 20, 11, 9]
print("The list is :")
print(my_list)
print("The function to swap the first and last elements is swapped")
print(list_swapping(my_list))

ผลลัพธ์ตัวอย่าง

The list is : [34, 21, 56, 78, 93, 20, 11, 9]
The function to swap the first and last elements is swapped
[9, 21, 56, 78, 93, 20, 11, 34]

คำอธิบาย

  • นิยามเมธอด list_swapping
  • รับ List เป็นพารามิเตอร์
  • สลับองค์ประกอบแรกและสุดท้ายของ List
  • คืนค่า List ผลลัพธ์
  • นอกฟังก์ชัน นิยาม List และแสดงบนคอนโซล
  • เรียกเมธอดส่ง List นี้เป็นพารามิเตอร์
  • แสดงผลลัพธ์บนคอนโซล