Reputation: 3383
In Python, I have two lists, ids
and gos
and both have the same length (i.e. equal number of lines), but gos can have multiple elements per line (i.e., it is a list of lists) while ids has only 1 element per line
For example:
ids = ['1','2','3']
gos = [['a','b','c'],['d', 'e'], ['f']]
I want to print out each id in ids as many times as there are go-elements in the gos list followed by one of the corresponding elements from gos list, and each time on a new line.
I hope this clarifies the output I am seeking:
'1' 'a'
'1' 'b'
'1' 'c'
'2' 'd'
'2' 'e'
'3' 'f'
Upvotes: 0
Views: 1740
Reputation: 202
I hope this is an easy way to do that
for i in range(len(gos)):
for k in gos[i]:
print ids[i], k
Output
1 a
1 b
1 c
2 d
2 e
3 f
Upvotes: 0
Reputation: 27321
Yet another way of doing it..
ids = "1 2 3".split()
gos = ['a b c'.split(), 'c d'.split(), ['f']]
import itertools
ig = [zip([i] * len(g), g)
for i, g in zip(ids, gos)]
for i, g in itertools.chain.from_iterable(ig):
print(i, g)
Upvotes: 0
Reputation: 8692
another way of doing this
from itertools import product,imap
ids = ['1','2','3']
gos = [['a','b','c'],['d', 'e'], ['f']]
for i in imap(product,ids,gos):
for j in i:
print j[0],j[1]
Upvotes: 0
Reputation: 4318
Use zip:
for i,g in zip(ids, gos):
for ge in g:
print i,ge
output:
1 a
1 b
1 c
2 d
2 e
3 f
Upvotes: 1
Reputation: 34146
You can try these simple nested for loops:
for i, e1 in enumerate(ids):
for e2 in gos[i]:
print e1, e2
Output:
1 a
1 b
1 c
2 d
2 e
3 f
Note: The enumerate
function is used to keep count of the index, which will be used to access to the corresponding element of gos
.
Upvotes: 0