Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

two for loops in one list comprehension separately [duplicate]

Tags:

python

list

def get_plus(x,y):
    return str(x) + y


seq_x = [1, 2, 3, 4]
seq_y = 'abc'
print([get_plus(x,y) for x in seq_x for y in seq_y])

#result // ['1a', '1b', '1c', '2a', '2b', '2c', '3a', '3b', '3c', '4a', '4b', '4c']

but, I'd like to make result like this

 #result // ['1a', '2b', '3c']

how can I do that?

like image 442
MGDG Avatar asked Jul 31 '19 12:07

MGDG


1 Answers

You can use zip to combine iterables into another iterable of pairs:

>>> zip([1,2,3], [9,8,7,6])
<zip object at 0x7f289a116188>
>>> list(zip([1,2,3], [9,8,7,6]))
[(1, 9), (2, 8), (3, 7)]

NOTE: The returned iterator stops when the shortest input iterable is exhausted.


>>> def get_plus(x, y):
...     return str(x) + y
... 
>>> seq_x = [1, 2, 3, 4]
>>> seq_y = 'abc'
>>> [get_plus(x,y) for x, y in zip(seq_x, seq_y)]
['1a', '2b', '3c']


>>> ['{}{}'.format(x,y) for x, y in zip(seq_x, seq_y)]  # Using str.format
['1a', '2b', '3c']
like image 161
falsetru Avatar answered Sep 23 '22 00:09

falsetru