gpt4 book ai didi

python - 如何在 3 个字符串的所有可能组合上运行代码

转载 作者:太空狗 更新时间:2023-10-30 02:28:34 25 4
gpt4 key购买 nike

我有 3 个字符串:

strand1 = "something"
strand2 = "something else"
strand3 = "something else again"

我想对这 3 个字符串的每种可能排列运行一些函数,例如:

案例一:

strand1 = "something else again"
strand2 = "something"
strand3 = "something else"

案例二

strand1 = "something else"
strand2 = "something else again"
strand3 = "something"

等...

我如何在 Python 中优雅地做到这一点?我考虑过将字符串放在一个数组中并使用 itertools 但它似乎在每次迭代时都会剪切字符串。

另一件需要考虑的事情是字符串存储在一个对象中。例如,我通过键入调用 strand1

strand1.aa

感谢您的帮助,我希望问题很清楚。

最佳答案

itertools 是正确的查找位置。您是否尝试过 itertools.permutations

查看 documentation for it .

itertools.permutations(iterable) 的方法会给你一个排列生成器,然后你可以使用 for 循环来处理每个排列。

from itertools import permutations

# Any iterable will do. I am using a tuple.
for permutation in permutations(('a', 'b', 'c')): # Use your strings
print(permutation) # Change print() to whatever you need to do with the permutation

这个样本产生

('a', 'b', 'c')
('a', 'c', 'b')
('b', 'a', 'c')
('b', 'c', 'a')
('c', 'a', 'b')
('c', 'b', 'a')

关于python - 如何在 3 个字符串的所有可能组合上运行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36430566/

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