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?
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With