목록은 순서가 지정되고 변경할 수 있는 모음입니다. Python에서 목록은 대괄호로 작성됩니다. 색인 번호를 참조하여 목록 항목에 액세스합니다. 음수 인덱싱은 끝에서 시작하는 것을 의미하고 -1은 마지막 항목을 나타냅니다. 범위를 시작할 위치와 끝낼 위치를 지정하여 인덱스 범위를 지정할 수 있습니다. 범위를 지정할 때 반환 값은 지정된 항목이 있는 새 목록이 됩니다.
예시
# triplets from list of words. # List of word initialization list_of_words = ['I', 'am', 'Vishesh', 'and', 'I', 'like', 'Python', 'programming'] # Using list comprehension List = [list_of_words[i:i + 3] for i in range(len(list_of_words) - 2)] # printing list print(List) # List of word initialization list_of_words = ['I', 'am', 'Vishesh', 'and', 'I', 'like', 'Python', 'programming'] # Output list initialization out = [] # Finding length of list length = len(list_of_words) # Using iteration for z in range(0, length-2): # Creating a temp list to add 3 words temp = [] temp.append(list_of_words[z]) temp.append(list_of_words[z + 1]) temp.append(list_of_words[z + 2]) out.append(temp) # printing output print(out)
출력
[['I', 'am', 'Vishesh'], ['am', 'Vishesh', 'and'], ['Vishesh', 'and', 'I'], ['and', 'I', 'like'], ['I', 'like', 'Python'], ['like', 'Python', 'programming']] [['I', 'am', 'Vishesh'], ['am', 'Vishesh', 'and'], ['Vishesh', 'and', 'I'], ['and', 'I', 'like'], ['I', 'like', 'Python'], ['like', 'Python', 'programming']]