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)
我怎样才能做到这一点?
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)
| 归档时间: |
|
| 查看次数: |
55 次 |
| 最近记录: |