Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

append elements from specific positions of a list to another lists in one line function

I need to generate M lists from another list with N=a*M elements (a>=1), so the nth element of i partition is added to the the nth position of the i new list (i=1..M, so the original list is splitted in equal parts of N/M length).

With an example is a lot easier to understand:
so supose that I have this list lg=[1,2,3,4,5,6,7,8,9], the result should be l1=[1,4,7], l2=[2,5,8], l3=[3,6,9]

I did it with this code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

lg=[1,2,3,4,5,6,7,8,9] # N=9
M=3
lr=[[] for _ in range(M)]

print(lr) # [[], [], []]
idx_lr = 0
for idx,el in enumerate(lg): # the enumerate is not necessary, was for testing purposes
  lr[idx_lr].append(el)
  idx_lr += 1
  if idx_lr == M:
    idx_lr = 0
print(lr) #[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

and it works, but, it’s an ugly code, there is a way to do it with one line function?

>Solution :

You can do this with a simple slice operation:

>>> lg=[1,2,3,4,5,6,7,8,9]
>>> [lg[i::3] for i in range(3)]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

The third part of the slice is the "step" between each element in the slice; it defaults to 1, but setting it to M makes it take every Mth element.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading