tri_num = []
for i in range(1, 10):
tri_num.append(i*(i+1)//2)
print(tri_num)
嗨,我正在学习 Python 课程,我们被要求编写一个列表理解,它创建与下面完全相同的列表,由上面的代码生成。 其输出如下:
[1]
[1, 3]
[1, 3, 6]
[1, 3, 6, 10]
[1, 3, 6, 10, 15]
[1, 3, 6, 10, 15, 21]
[1, 3, 6, 10, 15, 21, 28]
[1, 3, 6, 10, 15, 21, 28, 36]
[1, 3, 6, 10, 15, 21, 28, 36, 45]
我为列表理解编写了以下代码,并得出以下结果:
tri_num = [(i*(i+1)//2)for i in range (1, 10)]
print(tri_num)
`output:`
[1, 3, 6, 10, 15, 21, 28, 36, 45]
任何帮助或建议将不胜感激! 谢谢!
我尝试了此列表理解的多种变体,但没有成功。
tri_num = [(j*(j+1)//2) for i in range(1, 10) for j in range(1, i+1)]
print([tri_num[:i] for i in range(1, 10)])