在两个列表中逐个压缩

2024-04-24 11:13:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

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')]

有人能告诉我应该如何修改上面的代码以得到我想要的输出吗?你知道吗

谢谢


Tags: 代码zipprinttest1test2test3test4test5
3条回答

请在此列出您的作品:

 >>> a = [1, 2, 3, 4, 5]
 >>> b = ['test1', 'test2', 'test3', 'test4', 'test5']
 >>> [ (x,y) for x in a for y in b ]
 [(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

可以使用for循环

c = []
for i in a:
    for s in b:
        c.append((i, s))

或同等的列表理解

c = [(i,s) for i in a for s in b]

或者永远有用的itertools.product

import itertools

c = list(itertools.product(a, b))

相关问题 更多 >