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

falsetru
  • 357,413
  • 63
  • 732
  • 636
MGDG
  • 55
  • 4

3 Answers3

6

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']
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • 1
    Im not a fan of the arbitrary typelessness. I suggest either `str()` both, or just do: `return "{}{}".format(x,y)` for consistency. – Fallenreaper Jul 31 '19 at 12:48
  • @Fallenreaper, updated the answer to use `str.format` as you suggested. Thank you. – falsetru Jul 31 '19 at 12:50
0

Zip to the rescue. Killer one-liner:

>>> [''.join(str(col) for col in row) for row in zip([1,2,3,4], 'abc')]
['1a', '2b', '3c']
freakish
  • 54,167
  • 9
  • 132
  • 169
0
seq_x = [1, 2, 3, 4]
seq_y = 'abc'
print ([str(x)+y for x, y in zip(seq_x, seq_y)])

output:

['1a', '2b', '3c']
ncica
  • 7,015
  • 1
  • 15
  • 37