在GAE Python模板中迭代2個循環

[英]Iterate through 2 loops in GAE Python templates


I am using Jinja2 template in python for Google App Engine. I need to iterate through 2 lists list1 and list2 in the same loop in the html file. I tried using zip as described in some of the posts but it is not working. Something similar in C : for(i=0.j=0; I<len(list1) && j < len(list2) ; I++,j++)

我在python中使用Jinja2模板用於Google App Engine。我需要在html文件的同一循環中遍歷2個列表list1和list2。我嘗試使用一些帖子中描述的zip,但它不起作用。類似於C:for(i = 0.j = 0; I

Can anyone suggest some ways to implement the same?

任何人都可以提出一些實現相同的方法嗎?

2 个解决方案

#1


0  

If you have list1 and list2, you can use list and define it like this:

如果你有list1和list2,你可以使用list並像這樣定義它:

list = zip(list1[:min(len(list1), len(list2))], list2[:min(len(list1), len(list2))])

or better yet

還是更好

size = min(len(list1), len(list2))
list = zip(list1[:size], list2[:size])

Example:

>>> list1 = [1,2,3,4]
>>> list2 = [1,2,3,4,5,6,7]
>>> list = zip(list1[:min(len(list1), len(list2))], list2[:min(len(list1), len(list2))])
>>> list
[(1, 1), (2, 2), (3, 3), (4, 4)]

Note that zip only works with lists of equal length.

請注意,zip僅適用於長度相等的列表。

#2


0  

It sounds like you want to use itertools.product(list1, list2). This will create all combinations of list1 and list2.

聽起來你想使用itertools.product(list1,list2)。這將創建list1和list2的所有組合。

For example, if list1 = [1,2] and list2 = [1,2,3] then itertools.products(list1,list2) = [ (1,1),(2,1),(3,1),(2,1),(2,2),(2,3)]

例如,如果list1 = [1,2]和list2 = [1,2,3]則itertools.products(list1,list2)= [(1,1),(2,1),(3,1), (2,1),(2,2),(2,3)]


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/11/29/7251e7d7c50d6dfaa4d9d188b0ee45c3.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com