我有3个字符串:
strand1 = "something"
strand2 = "something else"
strand3 = "something else again"
我想对这3个字符串的每种可能排列运行一些函数,例如:
案例1:
strand1 = "something else again"
strand2 = "something"
strand3 = "something else"
案例2
strand1 = "something else"
strand2 = "something else again"
strand3 = "something"
等等......
我如何在Python中优雅地完成这项工作?我考虑将字符串放在一个数组中并使用itertools
,但它似乎在每次迭代时剪切字符串。
要考虑的另一件事是字符串存储在对象中。例如,我通过输入
来呼叫strand1
strand1.aa
感谢您的帮助,我希望问题很明确。
答案 0 :(得分:3)
itertools
是正确的选择。你试过itertools.permutations
吗?
关于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')
答案 1 :(得分:3)
您可以使用itertools.permutations
。如果函数有多个参数,您可以通过splat operator传递它们。
import itertools
def f(a, b, c):
print(a, b, c)
# o = get_my_object()
# seq = [o.a, o.b, o.c]
seq = ['s1', 's2', 's3']
for perm in itertools.permutations(seq):
f(*perm)
输出:
s1 s2 s3
s1 s3 s2
s2 s1 s3
s2 s3 s1
s3 s1 s2
s3 s2 s1