I am quite new to python, I was studying list comprehension but I am stuck how to initialize a nested list using a list comprehension like this
a = [[1,2,3],[4,5,6],[7,8,9]]
for example, I can use a list comprehension to initialize a list like this
var = [x for x in range(0,10)]
but I don't know to initialize nested list.
a = [[i * 3 + j + 1 for j in range(3)] for i in range(3)]
[[i, i+1, i+2] for i in range(1, 10, 3)]
# [[1,2,3], [4,5,6], [7,8,9]]
you can also do:
a = [[j+i for j in range(3)] for i in range(1,9,3)]
print (a)
output:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Kinda vague question, I'd say you could do for a series that is p
sets of n
numbers,
[ list(range(u+1,u+p+1)) for u in range(0,n*p,p) ]
However, as you're asking about nested comprehensions, I'll include this
aa = [1,2,3,4,5,6,7,8,9,10,11,12]
yourlist = [ [ aa[x] for x in range(x,x+3) ] for x in range(0,len(aa),3) ]
Which hands an x
to the inner nested comprehension as if in a regular for
loop
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.