user2294401
user2294401

Reputation: 387

How can i for loop in parallel in python

I have two lists

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

I want to display them on same lines

"list1 text"  "list2 text"

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

and so on

so that if list elements finish then it should display blank "" in front of it but other side shows its own elements like

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

Upvotes: 1

Views: 127

Answers (7)

jlanik
jlanik

Reputation: 939

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

Upvotes: 1

jlanik
jlanik

Reputation: 939

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

Upvotes: 1

John La Rooy
John La Rooy

Reputation: 304137

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

Upvotes: 1

Kousik
Kousik

Reputation: 22415

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

for more details please go through this link: Hidden features of Python

Upvotes: 1

Ronald Oussoren
Ronald Oussoren

Reputation: 2810

Itertools.izip_longest can be used to combine the two lists, the value None will be used as a placeholder value for "missing" items in the shorter list.

Upvotes: 1

Kiro
Kiro

Reputation: 949

Something like this?

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)+'"'

Out:

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

Upvotes: 3

Jared
Jared

Reputation: 26397

You can use izip_longest with a fillvalue of whitespace,

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

Upvotes: 4

Related Questions