Reputation: 349
So I got a list of lists (I don't wanna say a 2D list because it has different sizes)
mylist = [[0, 4, 3, 2, 1], [0, 3, 4, 1], [0, 4, 1], [0, 2, 1], [0, 3, 4, 1], [0,1]] #len(mylist) = 6
And I want to convert this list of list to a "3D list" every third element so I would get
newlist = [[[0, 4, 3, 2, 1], [0, 3, 4, 1], [0, 4, 1]], [[0, 2, 1], [0, 3, 4, 1], [0, 1]]]
Maybe it's a pretty basic question and I think I can do this using Numpy, but I'm trying to learn list comprehension and every example I seen so far it has the same amount of elements in every list, thank you in advance, and sorry if it's a simple question.
Upvotes: 0
Views: 439
Reputation: 44444
every example I seen so far it has the same amount of elements in every list,
That is because many present examples such that it takes an element from a source list, converts it (map it), and constructs a new transformed list. You can also have a conditional in list comprehension that will drop elements from destination list if a certain condition about the item being processed isn't met. You may want to see my other answer about list comprehension
There's one item to note: The "dimension" or shape of your list doesn't change when put through simple list comprehension. You might need to nest it, at the very least. Something like [[y for y in x] x for x in z]
But if you insist on using it, you'll have to explore using:
To answer your question: I see no need for list comprehension. Just plain old slide and list append:
newlist = [mylist[:3]] + [mylist[3:]]
print(newlist)
# [[[0, 4, 3, 2, 1], [0, 3, 4, 1], [0, 4, 1]], [[0, 2, 1], [0, 3, 4, 1], [0, 1]]]
.. note that the above is not a general solution by any stretch. You'll most likely want one of the two points above.
Here's a slightly more general solution. If you're learning about List Comprehension, it might take you a while to fully understand why this works :)
>>> items = list(range(20))
>>> it = iter(items)
>>> items_in_one_chunk = 4
>>> iters = [it] * items_in_one_chunk
>>> [list(x) for x in zip(*iters)]
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19]]
Upvotes: 1
Reputation: 97
You could use the slice() function for splitting your list every 3 elements. Have a look here for understanding its logic. Also this discussion is similar to what you want to achieve.
Upvotes: 1