在python中将循环转换为理解列表

时间:2018-05-23 05:52:51

标签: python list-comprehension

我在使用理解列表

编写以下循环时遇到问题
n = input( ' enter any number: ' )
a = []
for i in range(1, n+1):
    b = []
    for j in range(0, i):
        b.append( i + ((9 - j) * j) // 2)
    a.append(b)
print(a)

实际上问题是打印

1  
2 6    
3 7 10  
4 8 11 13  
5 9 12 14 15  
  if n = 5

4 个答案:

答案 0 :(得分:1)

您可以使用:

In [10]: n = 5
In [11]: [[i+((9-j)*j)//2 for j in range(0, i)] for i in range(1, n+1)]
Out[11]: [[1], [2, 6], [3, 7, 10], [4, 8, 11, 13], [5, 9, 12, 14, 15]]

答案 1 :(得分:1)

你的意思是这样吗?

alist = [[str(i + ((9 - j) * j) // 2) for j in range(i)] for i in range(1,n+1)]
print(*[' '.join(i) for i in alist],sep='\n')

注意:仅适用于python 3

将此用于python 2:

for i in alist:
    print(' '.join(i))

答案 2 :(得分:0)

你可以尝试,

In [1]: n = input( ' enter any number: ' )
enter any number: 10
In [2]: [[i + ((9 - j) * j) // 2 for j in range(0, i)] for i in range(1, n + 1)]
Out[2]:
[[1],
 [2, 6],
 [3, 7, 10],
 [4, 8, 11, 13],
 [5, 9, 12, 14, 15],
 [6, 10, 13, 15, 16, 16],
 [7, 11, 14, 16, 17, 17, 16],
 [8, 12, 15, 17, 18, 18, 17, 15],
 [9, 13, 16, 18, 19, 19, 18, 16, 13],
 [10, 14, 17, 19, 20, 20, 19, 17, 14, 10]]

In [3]:

答案 3 :(得分:0)

您可以尝试这样:

total = int(input( ' enter any number: ' ))
output = [[p + ((9 - q) * q) // 2 for q in range(p)] for p in range(1,total+1)]


for ele in output:
    print(ele)

输出:

 enter any number: 3
 [1]
 [2, 6]
 [3, 7, 10]