作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有 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/
我是一名优秀的程序员,十分优秀!