我正在尝试打印两个字符串的所有组合。

attributes = "old green".split()
persons = "car bike".split()

我的期望:
old car
old bike
green car
green bike

到目前为止我尝试过的:
from itertools import product

attributes = "old green".split()
persons = "car bike".split()

print([list(zip(attributes, p)) for p in product(persons,repeat=1)])

最佳答案

您必须将 persons attributes 传递给 product :

>>> [p for p in product(attributes, persons)]
[('old', 'car'), ('old', 'bike'), ('green', 'car'), ('green', 'bike')]

然后连接这些字符串:
>>> [' '.join(p) for p in product(attributes, persons)]
['old car', 'old bike', 'green car', 'green bike']

如果您想单独打印它们,您可以使用 for -loop 而不是列表理解:
for p in product(attributes, persons):
    print(' '.join(p))

关于python - 生成所有可能的字符串组合,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44013024/

10-14 10:28