Python - 从给定列表创建三元组的方法
pythonserver side programmingprogramming更新于 2025/9/17 7:08:17
列表是有序且可更改的集合。在 Python 中,列表用方括号书写。您可以通过引用索引号来访问列表项。负索引表示从末尾开始,-1 表示最后一项。您可以通过指定范围的起始位置和终止位置来指定索引范围。指定范围时,返回值将是包含指定项目的新列表。
示例
# 来自单词列表的三元组。 # 单词列表初始化 list_of_words = ['I', 'am', 'Vishesh', 'and', 'I', 'like', 'Python', 'programming'] # 使用列表推导 List = [list_of_words[i:i + 3] for i in range(len(list_of_words) - 2)] # 打印列表 print(List) # 单词列表初始化 list_of_words = ['I', 'am', 'Vishesh', 'and', 'I', 'like', 'Python', 'programming'] # 输出列表初始化 out = [] # 查找列表长度 length = len(list_of_words) # 使用迭代 for z in range(0, length-2): # 创建临时列表以添加 3 个单词 temp = [] temp.append(list_of_words[z]) temp.append(list_of_words[z + 1]) temp.append(list_of_words[z + 2]) out.append(temp) # 打印输出 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']]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

