Python 使用列表理解的嵌套 For 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3633140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:01:01  来源:igfitidea点击:

Nested For Loops Using List Comprehension

pythonfor-looplist-comprehension

提问by John Howard

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

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

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?

但是,我希望能够使用列表理解来做到这一点。我尝试了很多方法,但从未设法得到它。有谁知道如何做到这一点?

采纳答案by aaronasterling

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.

就像在问题中一样,for j...是外循环,for k...是内循环。

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.

从本质上讲,只需一个接一个地粘贴,您就可以在列表理解中拥有任意数量的独立“for x in y”子句。

回答by miles82

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。我认为它更清晰,尤其是当你有更多的输入迭代时。

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

回答by Stefan Gruenwald

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:

给你8种组合:

abc
abf
aec
aef
dbc
dbf
dec
def