一个列表理解中的两个for循环

MGD*_*GDG 5 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']
Run Code Online (Sandbox Code Playgroud)

但是,我想要这样的结果

 #result // ['1a', '2b', '3c']
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

fal*_*tru 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)]
Run Code Online (Sandbox Code Playgroud)

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']
Run Code Online (Sandbox Code Playgroud)