Skip to main content
 首页 » 编程设计

python之在两个列表中全部压缩

2025年05月04日14java哥

我有以下代码:

a = [1, 2, 3, 4, 5] 
b = ['test1', 'test2', 'test3', 'test4', 'test5'] 
c = zip(a, b) 
print c 

这给了我一个输出:

[(1, 'test1'), (2, 'test2'), (3, 'test3'), (4, 'test4'), (5, 'test5')] 

我真正想要的是这样的:

[(1, 'test1'), (1, 'test2'), (1, 'test3'), (1, 'test4'), (1, 'test5') 
 (2, 'test1'), (2, 'test2'), (2, 'test3'), (2, 'test4'), (2, 'test5') 
 (3, 'test1'), (3, 'test2'), (3, 'test3'), (3, 'test4'), (3, 'test5') 
 (4, 'test1'), (4, 'test2'), (4, 'test3'), (4, 'test4'), (4, 'test5') 
 (5, 'test1'), (5, 'test2'), (5, 'test3'), (5, 'test4'), (5, 'test5')] 

谁能告诉我应该如何修改上面的代码以获得我想要的输出?

谢谢

请您参考如下方法:

你想要的是Cartesian Product .

import itertools 
for i in itertools.product([1, 2, 3, 4, 5],['test1', 'test2', 'test3', 'test4', 'test5']): 
    print i