如果我有两个字符串,'abc'
和'def'
,我可以使用两个for循环获得它们的所有组合:
for j in s1:
for k in s2:
print(j, k)
但是,我希望能够使用列表理解来做到这一点。我试过很多方法,但从来没有成功过。有人知道怎么做吗?
发布于 2010-09-03 12:58:52
lst = [j + k for j in s1 for k in s2]
或
lst = [(j, k) for j in s1 for k in s2]
如果你想要元组。
与问题中一样,for j...
是外部循环,for k...
是内部循环。
从本质上讲,只要一个接一个地粘贴,你就可以在列表理解中拥有任意多个独立的'for x in y‘子句。
要使其更具可读性,请使用多行:
lst = [
j + k # result
for j in s1 # for loop
for k in s2 # for loop
# condition
]
发布于 2010-09-03 15:53:08
由于这本质上是一个笛卡尔产品,因此您也可以使用itertools.product。我认为它更清晰,特别是当你有更多的输入可迭代的时候。
itertools.product('abc', 'def', 'ghi')
发布于 2014-03-25 04:53:53
也可以尝试递归:
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))
给出了8种组合:
abc
abf
aec
aef
dbc
dbf
dec
def
https://stackoverflow.com/questions/3633140
复制相似问题