创建从 a(含)到 b(含)的整数列表。
例子:integers(2,5)
返回 [2, 3, 4, 5]
.
我知道这可能很容易,但我似乎无法做任何事情。
最佳答案
>>> def integers(a, b):
return list(range(a, b+1))
>>> integers(2, 5)
[2, 3, 4, 5]
解释您自己的解决方案:
can you explain to me why in some programs you have to include
[i]
and some it is justi
def integers(a,b): list = [] for i in range(a, b+1): list = list + [i]
i
指数字本身; [i]
是一个只有一个元素的列表,i
.使用 +
时列表操作符,Python 可以连接两个列表,所以 [1, 2] + [3, 4]
是 [1, 2, 3, 4]
.然而,不可能只将单个元素(或在这种情况下为数字)添加到现有列表中。这样做会导致 TypeError
.您可以做的不是与单元素列表连接,而是使用具有相同名称的方法简单地附加元素:
list.append(i)
最后一点,你不应该命名你的变量
list
(或 dict
或 str
等),因为这将在本地覆盖对内置函数/类型的引用。
关于python-3.x - 在python中创建从a到b的整数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13849618/