Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

목록의 첫 번째 요소와 마지막 요소를 교환하는 Python 프로그램


이 기사에서는 아래 주어진 문제 설명에 대한 솔루션에 대해 알아볼 것입니다.

문제 설명 − 목록이 주어졌으므로 마지막 요소를 첫 번째 요소로 교체해야 합니다.

아래에 논의된 바와 같이 문제를 해결하기 위한 4가지 접근 방식이 있습니다-

접근법 1 - 무차별 대입 접근

def swapLast(List):
   size = len(List)
   # Swap operation
   temp = List[0]
   List[0] = List[size - 1]
   List[size - 1] = temp
   return List
# Driver code
List = ['t','u','t','o','r','i','a','l']
print(swapLast(List))

출력

['t','u','t','o','r','i','a','l']

접근법 2 - 음수 색인을 사용한 무차별 대입 접근

def swapLast(List):
   size = len(List)
   # Swap operation
   temp = List[0]
   List[0] = List[-1]
   List[-1] = temp
   return List
# Driver code
List = ['t','u','t','o','r','i','a','l']
print(swapLast(List))

출력

['t','u','t','o','r','i','a','l']

접근법 3 - 튜플의 패킹 및 풀기

def swapLast(List):
   #packing the elements
   get = List[-1], List[0]
   # unpacking those elements
   List[0], List[-1] = get
   return List
# Driver code
List = ['t','u','t','o','r','i','a','l']
print(swapLast(List))

출력

['t','u','t','o','r','i','a','l']

접근법 4 - 튜플의 패킹 및 풀기

def swapLast(List):
   #packing the elements
   start, *middle, end = List
   # unpacking those elements
   List = [end, *middle, start]
   return List
# Driver code
List = ['t','u','t','o','r','i','a','l']
print(swapLast(List))

출력

['t','u','t','o','r','i','a','l']

결론

이 기사에서는 목록의 첫 번째 요소와 마지막 요소를 교환하는 방법에 대해 배웠습니다.