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

2024-09-29 22:03:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有三根弦:

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.aa

谢谢你的帮助,我希望问题是清楚的。你知道吗


Tags: 对象函数字符串键入数组事情elsesomething
2条回答

您可以使用^{}。如果函数有多个参数,可以通过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

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')

相关问题 更多 >

    热门问题