I want to generate the list of list [[1,2,3],[4,5,6]]
I have attached some python codes but I do not know what to pick among them in terms of efficiency:
[[y x for x in range(3)] for y in [1,4]]
[[y for y in range(z, z 3)] for z in [1,4]]
[[y, y 1, y 2] for y in [1,4]]
They all generate the required list however I do not feel satisfied with how they are written (since they are all dependent on getting values from the list [1,4]) and considering that I am only a beginner in the Python language. Can you also recommend me a good way to generate the list required? Thank you
CodePudding user response:
[[y x for x in range(3)] for y in [1,4]]
In this code, Giving the value 4 is not the best way because in order to print a list like this
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18], [19, 20, 21], [22, 23, 24], [25, 26, 27], [28, 29, 30]]
you might have to write
[[y x for x in range(3)] for y in [1,4,7,10,13,16,19,22,25,28]]
which is not an easy and generalised code.Instead you can write
[[ x for x in range(y,y 3)] for y in range(1,6,3)]
or
[[ x for x in range(y,y 3)] for y in range(1,n,3)]