0

I have a list of elements, and I need to generate a bunch of these:

<div class="row">
    <div class="row-element"> datapoint 1</div>
    <div class="row-element"> datapoint 2</div>
    <div class="row-element"> datapoint 3</div>
    <div class="row-element"> datapoint 4</div>
</div>

.... # And so on

It gets tricky trying to do this. The list some_list length can be odd or even too. Every div row should have at most four child row-elements.

for i,x in enumerate(some_list):
    if i%4 == 0:
         print '<div class="row">'
         tmp = i+4

    print '<div class="row-element">' + x + '</div>'

    if tmp-1==i:
        print '</div>'

This sort of works only if the list is evenly divisible by 4, and also it's really ugly code-wise.

How would I generate enclosing div tags for even and odd number elements cleanly in python?

user21398
  • 1,473
  • 4
  • 18
  • 31
  • what functions can you use? you said you prefer code using `for` but you use `enumerate` in your implementation? – laike9m Jan 15 '14 at 05:28

2 Answers2

1

load your document to something like lxml.html document and use the technique from this great answer

>>> list(chunks(range(0, 11), 4))
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10]]
Community
  • 1
  • 1
Guy Gavriely
  • 11,228
  • 6
  • 27
  • 42
  • Hm.. I'm using a python web framework though, and I'm trying to dynamically generate div tags using their templates. They limit what python code can run in the template, so simple for loops would be better for me. – user21398 Jan 15 '14 at 05:16
  • 1
    Follow the link he included. `chunks` is just a `for` loop inside a generator using `yield` when needed. Then you just need your own `for` loops to do the printing. This is by far the better answer than the one that crazy @mhlester guy could come up with. And your web framework can't possibly disallow this code. – mhlester Jan 15 '14 at 05:35
0

I don't know if this is actually cleaner... I'm printing </div> in two locations which I don't much like.

for i, x in enumerate(some_list):
    if not i % 4:
        if i:
            print '</div>'
        print '<div class="row">'

    print '<div class="row-element">' + x + '</div>'

print '</div>'
mhlester
  • 22,781
  • 10
  • 52
  • 75