在 Python 中将元素范围分配给列表
pythonserver side programmingprogramming更新于 2025/12/25 21:32:17
列表是 Python 中非常常用的数据容器。在使用列表时,我们可能会遇到列表元素可能是数字序列的情况。我们可以使用许多 Python 函数将此数字序列添加到列表中。在本文中,我们将探索不同的方法。
使用 range 和 extend
extent 函数允许我们增加列表中元素的数量。将使用范围函数并将扩展应用于列表,以便所有所需的数字序列都添加到列表末尾。
示例
listA = [55,91,3]
# 给定列表
print("Given list: ", listA)
# 应用扩展()
listA.extend(range(4))
# 打印结果
print("新列表:",listA)
输出
运行上述代码得到以下结果 −
Given list: [55, 91, 3] The new list : [55, 91, 3, 0, 1, 2, 3]
使用 * 和 range
* 运算符可以扩展列表,其优点是可以在任何位置添加元素。我们还再次使用 range 函数来处理数字序列。
示例
listA = [55,91,3]
# 给定列表
print("Given list: ", listA)
# 应用 *
Newlist = [55,91,*range(4),3]
# 打印结果
print("The new list : ",Newlist)
输出
运行上述代码得到以下结果 −
Given list: [55, 91, 3] The new list : [55, 91, 0, 1, 2, 3, 3]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

