列表是有序且可更改的集合。在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']]