【发布时间】:2011-04-07 16:23:42
【问题描述】:
如果我有两个字符串,'abc' 和 'def',我可以使用两个 for 循环获得它们的所有组合:
for j in s1:
for k in s2:
print(j, k)
但是,我希望能够使用列表理解来做到这一点。我尝试了很多方法,但从未设法得到它。有谁知道怎么做?
【问题讨论】:
标签: python for-loop list-comprehension
如果我有两个字符串,'abc' 和 'def',我可以使用两个 for 循环获得它们的所有组合:
for j in s1:
for k in s2:
print(j, k)
但是,我希望能够使用列表理解来做到这一点。我尝试了很多方法,但从未设法得到它。有谁知道怎么做?
【问题讨论】:
标签: python for-loop list-comprehension
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
]
【讨论】:
L1 = [[[e1, e2, ...], ...], ...] -> [ e for L2 in L1 for L3 in L2 for e in L3 ]
for 语句的顺序与您将其编写为两个单独的行上的两个 for 循环一样。
lst = [j+k if BLAHBLAHBLAH for j in s1 for k in s2] 什么的
由于这本质上是一个笛卡尔积,您也可以使用itertools.product。我认为它更清晰,尤其是当您有更多输入迭代时。
itertools.product('abc', 'def', 'ghi')
【讨论】:
也试试递归:
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
【讨论】: