I have a list [1, 2, 3, 4, ..., n]
. In a one-liner list comprehension, how can I print the progression [1]
, [1, 2]
, [1, 2, 3]
, [1, 2, 3, 4]
, ..., [1, 2, 3, 4, ..., n-1]
, where n
represents an arbitrary natural number?
CodePudding user response:
Now if you want this principle to operate on any starting list (not necessarily [1,2,...]), you can do this:
rawlist=['a','b','c','d']
newlist=[rawlist[:i] for i in range(1,len(rawlist) 1)]
CodePudding user response:
Try this:
n = 10
res = [list(range(1,i)) for i in range(2,n 1)]
print(res)
Output:
[
[1], # range(1, 2)
[1, 2], # range(1, 3)
[1, 2, 3],
[1, 2, 3, 4],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5, 6],
[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5, 6, 7, 8],
[1, 2, 3, 4, 5, 6, 7, 8, 9] # range(1, 10)
]
CodePudding user response:
How about a for loop in a for loop?
n = 10
print([[x for x in range(1,i 1)] for i in range(1,n 1)])
This prints an array of the numbers 1 to i for each value of i in the range 1 to n.
CodePudding user response:
This should give you every list from [1] to [1,...n-1]
[print([x for x in range(1, y 1)]) for y in range(1, n)]
CodePudding user response:
Starting with our [1, ..., n]
list, where n
in this case is 5
:
>>> a_list = list(range(1, 6))
>>> a_list
[1, 2, 3, 4, 5]
we can just iterate over the list and create another list for each number, with the last one ending in n-1
:
>>> print(*[list(range(1, x)) for x in a_list[1:]], sep=", ")
[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]
Or, doing it based on n
directly rather than a_list
:
>>> n = 5
>>> print(*[list(range(1, x)) for x in range(2, n 1)], sep=", ")
[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]
Note that using a list comprehension is not necessary; you can replace the outer []
in both examples with ()
(i.e. a parenthesized generator expression rather than a list comprehension) and it will print exactly the same thing.