作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
创建从 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/
我是一名优秀的程序员,十分优秀!