J'ai du mal à écrire la boucle suivante en utilisant la liste de compréhension

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)

En fait, la question est d'imprimer

1  
2 6    
3 7 10  
4 8 11 13  
5 9 12 14 15  
  if n = 5
-5
GUNJAN ARORA 23 mai 2018 à 08:52

4 réponses

Meilleure réponse

Tu veux dire comme cela?

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')

Remarque: uniquement pour python 3

Utilisez ceci pour python 2:

for i in alist:
    print(' '.join(i))
1
fahadh4ilyas 23 mai 2018 à 06:00

Vous pouvez utiliser:

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
llllllllll 23 mai 2018 à 05:54

Tu peux essayer,

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]:
0
Nishant Nawarkhede 23 mai 2018 à 06:02

Vous pouvez essayer comme ceci:

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)

Production:

 enter any number: 3
 [1]
 [2, 6]
 [3, 7, 10]
0
kvmahesh 23 mai 2018 à 06:00