Python 在两个列表中逐个压缩

Python 在两个列表中逐个压缩,python,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')

我有以下代码:

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')]
谁能告诉我应该如何修改上述代码以获得所需的输出


谢谢这里列出理解的工作:

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

请在此列出您的作品:

 >>> 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')]
你想要的是这个

你想要的是这个


您可以使用
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))

您可以使用
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))

笛卡尔合并是我在SQL中应该做的,但我不确定如何在Python中进行。谢谢。笛卡尔合并是我在SQL中应该做的,但我不知道如何在Python中进行。谢谢