[英]all combinations of items in a list. all containing alle items
looking for an easy way to get all combinations input: list of strings寻找一种简单的方法来获取所有组合输入:字符串列表
list = ["a", "b", "c", "d"]
output: nested list of strings output:字符串的嵌套列表
[["abcd"],["abc", "d"],["ab","cd"],["a","bcd"],["ab","c","d"],["a","bc","d"],["a","b","cd"],["a","b","c","d"]]
You can use recursion with a generator:您可以将递归与生成器一起使用:
def combo(d):
yield d
if len(d) > 1:
for i in range(len(d)-1):
yield from combo([*d[:i], d[i]+d[i+1], *d[i+2:]])
print(list(set(map(tuple, combo(["a", "b", "c", "d"])))))
Output: Output:
[('a', 'b', 'c', 'd'), ('abcd',), ('ab', 'c', 'd'), ('abc', 'd'), ('a', 'b', 'cd'), ('ab', 'cd'), ('a', 'bcd'), ('a', 'bc', 'd')]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.