gpt4 book ai didi

python - 生成所有可能的字符串组合

转载 作者:行者123 更新时间:2023-11-28 21:42:12 26 4
gpt4 key购买 nike

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

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 循环代替列表理解:

for p in product(attributes, persons):
print(' '.join(p))

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com