如何将列表中的字符串与列表理解相结合?
How to combine strings in list with a list comprehension?
例如:
s = ["ab", "cd"]
# expected output ac, ad, bc, bd
# This is easy
print([i+j for i in s[0] for j in s[1]])
# ['ac', 'ad', 'bc', 'bd']
但是当列表的长度大于two.How时,如何通过列表理解来实现?
s = ["ab", "cd", "ef"]
应该给ace, acf, ade, adf, bce, bcf, bde, bdf
。(如果我们不使用递归,如何使用for循环来实现?)
您要查找的是这些序列的产物。 itertools.product
就是这样做的。唯一复杂的是将序列转回字符串,您可以使用 join()
:
from itertools import product
s = ["ab", "cd", "ef"]
list(map(''.join, product(*s)))
# ['ace', 'acf', 'ade', 'adf', 'bce', 'bcf', 'bde', 'bdf']
如果您愿意,也可以使用列表理解:
[''.join(t) for t in product(*s)]
你可以当然可以自己用一个简单的递归函数来完成。这可能看起来像:
s = ["ab", "cd", "ef"]
def product(l):
if len(l) == 0:
yield ''
return
start, *rest = l
for c in start:
for sublist in product(rest):
yield c + sublist
list(product(s))
# ['ace', 'acf', 'ade', 'adf', 'bce', 'bcf', 'bde', 'bdf']
例如:
s = ["ab", "cd"]
# expected output ac, ad, bc, bd
# This is easy
print([i+j for i in s[0] for j in s[1]])
# ['ac', 'ad', 'bc', 'bd']
但是当列表的长度大于two.How时,如何通过列表理解来实现?
s = ["ab", "cd", "ef"]
应该给ace, acf, ade, adf, bce, bcf, bde, bdf
。(如果我们不使用递归,如何使用for循环来实现?)
您要查找的是这些序列的产物。 itertools.product
就是这样做的。唯一复杂的是将序列转回字符串,您可以使用 join()
:
from itertools import product
s = ["ab", "cd", "ef"]
list(map(''.join, product(*s)))
# ['ace', 'acf', 'ade', 'adf', 'bce', 'bcf', 'bde', 'bdf']
如果您愿意,也可以使用列表理解:
[''.join(t) for t in product(*s)]
你可以当然可以自己用一个简单的递归函数来完成。这可能看起来像:
s = ["ab", "cd", "ef"]
def product(l):
if len(l) == 0:
yield ''
return
start, *rest = l
for c in start:
for sublist in product(rest):
yield c + sublist
list(product(s))
# ['ace', 'acf', 'ade', 'adf', 'bce', 'bcf', 'bde', 'bdf']