![](/img/trans.png)
[英]How to create all possible subsets of given combination of letters in a list?
[英]How to generate every possible combination of a string when given a list of values
假设我有一个值列表,此列表可以是任意长度:
"100","200","300","400","500", ...
我有一个模板字符串,其中包含一些需要替换的标记:
"@token1@-@token2@-@token3@-....-@tokenN@"
使用值列表,如何生成模板中值的所有可能组合?
值可以多次使用,因此结果可能是“ 100-100-100”。 考虑到可变令牌数量的方法的加分!
编辑:删除固定数量的令牌版本
利用递归,只是为了好玩:
r($values,false,$numtokens); // false to get 100-100-100 as well.
function r($values,$unique=true,$depth=3,$collect=array())
{
if ( $depth == 0 )
{
print implode("-",$collect)."\n";
} else {
foreach ( $values as $id=>$t )
{
if ( $unique ) unset($values[$id]);
r($values,$unique,$depth-1,array_merge($collect,array($t)));
if ( $unique ) $values[$id] = $t;
}
}
}
(这可能需要针对不同的语言进行一些调整)
蟒蛇:
from itertools import permutations
list_of_values = ["100","200","300","400","500"]
template = "%s-%s-%s"
for p in permutations(list_of_values,3):
print(template % p)
如果您不希望以“ 500-400-300”和“ 300-400-500”为例,则可以组合而不是排列。
假设值可以重复:
#!/usr/bin/env python
VALUES=['100','200','300','400','500']
TOKEN='@token%d@'
TARGET="@token1@-@token2@-@token3@"
def rep(n,target):
src=TOKEN%n
if src not in target:
return [target]
ret = []
for v in VALUES:
ret += rep(n+1, target.replace(src,v))
return ret
print rep(1,TARGET)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.