2013-04-26 34 views
1

迴路並聯我有兩個列表我怎樣才能在巨蟒

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> 
+0

http://docs.python.org/2/library/functions.html#zip – squiguy 2013-04-26 06:14:39

+1

順便說一句,這不是所謂的「並行循環」。該詞主要是指並行計算。 – Elazar 2013-04-26 06:21:26

回答

4

您可以使用izip_longest與空白的fillvalue

>>> 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 
+0

我真的不知道如何可能。你必須向我們展示你的代碼。 – Kiro 2013-04-26 06:29:59

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" 
1

Itertools.izip_longest可以用來將兩個清單合併,該值都不會被用作「失蹤」,在較短的列表項的佔位符值。

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

+2

這是嵌套兩個循環,這似乎並不是要求的。順便說一下,你可以在itertools.product(l1,l2)中使用'for i:'來做同樣的事情 – 2013-04-26 06:46:26

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> 
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 
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