This is basic "for loop" pattern printing code as follows:
for i in range (1,5):
for j in range (i, 5):
print(j , end='')
print()
output:
1234
234
34
4
But I want the same as the above output using same logic using the List Comprehension.
for list Comprehension.
I tried:
[print(j,end='') for i in range(1,5) for j in range(i,5)]
and output is:
1234234344
Don't use a list comprehension for side effects , use a plain for-loop instead, ie your original code.
But here's how you would do it, by using unpacking instead of a second loop:
[print(*range(i, 5), sep='') for i in range(1, 5)]
So you could do this instead:
for i in range(1, 5):
print(*range(i, 5), sep='')
You can approach this by using a function instead:
def myfn(i):
for j in range(i,5):
print(j,end='')
print()
[myfn(i) for i in range(1,5) ]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.