我如何在python中并行循环

时间:2013-04-26 06:12:22

标签: python loops

我有两个列表

l1= [1,2,3,4,5,6,7]
l2 = [1,2,3,4,5,6,7,8,9,77,66,]

我想在同一行显示它们

"list1 text"  "list2 text"

l1-1   , l2-1
l1-2   , l2-2

等等

因此,如果列表元素完成,那么它应该在它前面显示空白"",但是其他方面显示它自己的元素,如

for a,b in l1,l2
     <td>a</td><td> b </td>

7 个答案:

答案 0 :(得分:4)

您可以将izip_longestfillvalue空格一起使用

>>> from itertools import izip_longest
>>> for a,b in izip_longest(l1,l2,fillvalue=' '):
...     print a,b
... 
1 1
2 2
3 3
4 4
5 5
6 6
7 7
  8
  9
  77
  66

答案 1 :(得分:3)

这样的东西?

from itertools import izip_longest
l1= [1,2,3,4,5,6,7]
l2 = [1,2,3,4,5,6,7,8,9,77,66,]

for a,b in izip_longest(l1,l2, fillvalue=''):
    print '"'+str(a)+'"','"'+str(b)+'"'

输出:

"1" "1"
"2" "2"
"3" "3"
"4" "4"
"5" "5"
"6" "6"
"7" "7"
"" "8"
"" "9"
"" "77"
"" "66"

答案 2 :(得分:1)

Itertools.izip_longest可用于组合两个列表,值None将用作较短列表中“缺失”项的占位符值。

答案 3 :(得分:1)

>>>l1= [1,2,3,4,5,6,7]
>>l2 = [1,2,3,4,5,6,7,8,9,77,66,]
>>>n = ((a,b) for a in l1 for b in l2)
>>>for i in n:
       i

有关详情,请浏览此链接:     Hidden features of Python

答案 4 :(得分:1)

>>> l1= [1,2,3,4,5,6,7]
>>> l2 = [1,2,3,4,5,6,7,8,9,77,66,]
>>> def render_items(*args):
...     return ''.join('<td>{}</td>'.format('' if i is None else i) for i in args)
... 
>>> for item in map(render_items, l1, l2):
...     print item
... 
<td>1</td><td>1</td>
<td>2</td><td>2</td>
<td>3</td><td>3</td>
<td>4</td><td>4</td>
<td>5</td><td>5</td>
<td>6</td><td>6</td>
<td>7</td><td>7</td>
<td></td><td>8</td>
<td></td><td>9</td>
<td></td><td>77</td>
<td></td><td>66</td>

答案 5 :(得分:1)

l1= [1,2,3,4,5,6,7]
l2 = [1,2,3,4,5,6,7,8,9,77,66]
maxlen = max(len(l1),len(l2))
l1_ext = l1 + (maxlen-len(l1))*[' ']
l2_ext = l2 + (maxlen-len(l2))*[' ']
for (a,b) in zip(l1_ext,l2_ext):
    print a,b

答案 6 :(得分:1)

l1= [1,2,3,4,5,6,7]
l2 = [1,2,3,4,5,6,7,8,9,77,66]
for (a,b) in map(lambda a,b:(a or ' ',b or ' '), l1, l2):
    print a,b