-4

I have objects list:

l = [1, 2, 3, 4, 5, 6]

i find some snippet.. http://herself.movielady.net/2008/07/16/split-list-to-columns-django-template-tag/

but they split like this:

[1, 2] [3, 4] [5, 6]

i need split list like this:

l1 = [1, 4]
l2 = [2, 5]
l3 = [3, 6]

Please, help build right templatetag.

timgeb
  • 64,821
  • 18
  • 95
  • 124
macgera
  • 299
  • 2
  • 10
  • What have you tried before asking? Did you try to change the snippet to get what you want? – Maxime Lorant Jun 04 '14 at 12:03
  • In that linked question, many answers will show you how to do it the way you don’t want to, but there are some, for example [this one](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python/21767522#21767522) which will give you your desired output. – poke Jun 04 '14 at 12:10
  • Is this question about splitting the list (try `[[l[k] for k in range(i, len(l), N)] for i in range(N)]`) or about building the Django template? – tobias_k Jun 04 '14 at 12:11
  • Also: [Equally distribute a list in python](http://stackoverflow.com/questions/22905030/equally-distribute-a-list-in-python) – poke Jun 04 '14 at 12:12
  • tobias_k i mean build Django templates.. – macgera Jun 04 '14 at 13:28
  • http://stackoverflow.com/users/1433392/maxime-lorant of course i try.. but have errors, maybe i not good understand how templatetags works – macgera Jun 04 '14 at 13:29

2 Answers2

1

You could gather your lists l1, l2 l3 in another list using a list comprehension, and afterwards do something to them. For example:

l = [1, 2, 3, 4, 5, 6]
x = [[l[i]] + [l[i+3]] for i in range(len(l) - 3)]
for a in x:
    print(a)

will get you

[1, 4]
[2, 5]
[3, 6]

If you know x contains three lists, you can assign l1, l2, l3 with

l1, l2, l3 = x

Of course, you could just manually assign l1, l2, l3 too.

l1 = [l[0]] + [l[3]]
...
timgeb
  • 64,821
  • 18
  • 95
  • 124
1
h = int(len(l)/2)
l1, l2, l3 = zip( l[:h], l[h:] )

l[:h] is the first half and l[h:] the second half. See list slices.

>>> l[:h], l[h:]
([1, 2, 3], [4, 5, 6])

Then the zip function, see zip.

>>> zip([1, 2, 3], [4, 5, 6])
[(1, 4), (2, 5), (3, 6)]
pacholik
  • 7,596
  • 8
  • 43
  • 50
  • It splits the original list in two and zips them together. Clever, but lacks an explanation. – Davidmh Jun 04 '14 at 12:53
  • This is a clever solution for the example problem, but fails for `l == [1,2,3,4,5,6,7]` assuming that the OP wants to get `[1,4], [2,5], [3,6], [4,7]` for such a list. Also, your `l1, l2, l3` are tuples (which of course could be changed to lists easily). – timgeb Jun 04 '14 at 13:30