简体   繁体   中英

Django iterate zip from same position in lists

first I zip all my lists just like

 books= zip(*bookName, *detail)

the length of bookbName and detail is same, and I want to get the table like

  {% for bookName, detail, in books %}
            <tr>
                <td>{{bookName}}</td>
                <td>{{detail}}</td>
            </tr>
        {% endfor %}

As I can not confirm the length of bookName and detail, I got the error message like "Need 3 values to unpack in for loop; got 5. "

I tried

{% for record in books %}
  <tr>
    {% for item in record %}
      <td>{{ item }}</td>
    {% endfor %}
  </tr>
{% endfor %}

but the result is get detail after all the bookname show. How can I get the table when I got first bookname then I can get the first book's detail?

for example the input list is

bookname: ["a", "b"]
detail:["fiction", "action"]

I want to get to table like

bookname  detail
  a        fiction
  b        action

I hope this clears your doubt and query:

bookname = ["a", "b"]
detail = ["fiction", "action"]

books1 = zip(bookname, detail)
print(list(books1))

# OUTPUT:
# [('a', 'fiction'), ('b', 'action')]

books2 = zip(*bookname, *detail)
print(list(books2))

# OUTPUT:
# [('a', 'b', 'f', 'a')]

Results after running for loop:

bookname = ["a", "b"]
detail = ["fiction", "action"]

books1 = zip(bookname, detail)

for name1, det1 in books1:
    print(name1, det1)

# OUTPUT:
# a fiction
# b action

books2 = zip(*bookname, *detail)

for name2, det2 in books2:
    print(name2, det2)

# ValueError: too many values to unpack (expected 2)

EDIT:

HTML:

  {% for bookName, detail in books1 %}
            <tr>
                <td>{{bookName}}</td>
                <td>{{detail}}</td>
            </tr>
        {% endfor %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM