Nested For Loops Using List Comprehension

2019-01-07 05:46发布

If I had two strings, 'abc' and 'def', I could get all combinations of them using two for loops:

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

However, I would like to be able to do this using list comprehension. I've tried many ways, but have never managed to get it. Does anyone know how to do this?

3条回答
Evening l夕情丶
2楼-- · 2019-01-07 05:58

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')
查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-07 06:10

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
查看更多
三岁会撩人
4楼-- · 2019-01-07 06:22
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.

查看更多
登录 后发表回答