List는 중요한 컨테이너이며 웹 개발뿐만 아니라 일상적인 프로그래밍의 거의 모든 코드에서 사용됩니다. 사용할수록 목록을 마스터해야 하는 요구 사항도 많아지므로 작업에 대한 지식이 필요합니다.
예
# using slice # initializing list test_list = [1, 4, 6, 7, 2] # printing original list print ("Original list : " + str(test_list)) # using slicing to left rotate by 3 test_list = test_list[3:] + test_list[:3] # Printing list after left rotate print ("List after left rotate by 3 : " + str(test_list)) # using slicing to right rotate by 3 # back to Original test_list = test_list[-3:] + test_list[:-3] # Printing after right rotate print ("List after right rotate by 3(back to original) : " + str(test_list)) # using list comprehension # initializing list test_list = [1, 4, 6, 7, 2] # printing original list print ("Original list : " + str(test_list)) # using list comprehension to left rotate by 3 test_list = [test_list[(i + 3) % len(test_list)] for i, x in enumerate(test_list)] # Printing list after left rotate print ("List after left rotate by 3 : " + str(test_list)) # using list comprehension to right rotate by 3 # back to Original test_list = [test_list[(i - 3) % len(test_list)] for i, x in enumerate(test_list)] # Printing after right rotate print ("List after right rotate by 3(back to original) : " + str(test_list)) # using rotate() from collections import deque # initializing list test_list = [1, 4, 6, 7, 2] # printing original list print ("Original list : " + str(test_list)) # using rotate() to left rotate by 3 test_list = deque(test_list) test_list.rotate(-3) test_list = list(test_list) # Printing list after left rotate print ("List after left rotate by 3 : " + str(test_list)) # using rotate() to right rotate by 3 # back to Original test_list = deque(test_list) test_list.rotate(3) test_list = list(test_list) # Printing after right rotate print ("List after right rotate by 3(back to original) : " + str(test_list))
출력
Original list : [1, 4, 6, 7, 2] List after left rotate by 3 : [7, 2, 1, 4, 6] List after right rotate by 3(back to original) : [1, 4, 6, 7, 2] Original list : [1, 4, 6, 7, 2] List after left rotate by 3 : [7, 2, 1, 4, 6] List after right rotate by 3(back to original) : [1, 4, 6, 7, 2] Original list : [1, 4, 6, 7, 2] List after left rotate by 3 : [7, 2, 1, 4, 6] List after right rotate by 3(back to original) : [1, 4, 6, 7, 2]