使用列表内涵为循环嵌套

如果我有两个字符串,'abc''def',我可以使用两个 for 循环得到它们的所有组合:

for j in s1:
for k in s2:
print(j, k)

不过,我希望能够使用列表内涵来做到这一点。我试了很多方法,但都没有成功。有人知道怎么做吗?

91294 次浏览
lst = [j + k for j in s1 for k in s2]

or

lst = [(j, k) for j in s1 for k in s2]

if you want tuples.

Like in the question, for j... is the outer loop, for k... is the inner loop.

Essentially, you can have as many independent 'for x in y' clauses as you want in a list comprehension just by sticking one after the other.

To make it more readable, use multiple lines:

lst = [
j + k         # result
for j in s1   # for loop
for k in s2 # for loop
# condition
]

Since this is essentially a Cartesian product, you can also use itertools.product. I think it's clearer, especially when you have more input iterables.

itertools.product('abc', 'def', 'ghi')

Try recursion too:

s=""
s1="abc"
s2="def"
def combinations(s,l):
if l==0:
print s
else:
combinations(s+s1[len(s1)-l],l-1)
combinations(s+s2[len(s2)-l],l-1)


combinations(s,len(s1))

Gives you the 8 combinations:

abc
abf
aec
aef
dbc
dbf
dec
def

It's just a ready-to-go version of @miles82 answer (please give credit where it's due):

from itertools import product
list(map(list, product('abc', 'def') ))

Output:

[['a', 'd'],
['a', 'e'],
['a', 'f'],
['b', 'd'],
['b', 'e'],
['b', 'f'],
['c', 'd'],
['c', 'e'],
['c', 'f']]


In case you wondered why we need list(map(list - itertools.product returns an iterator.