简体   繁体   English

列表中项目的所有组合。 所有包含所有项目

[英]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.

相关问题 获取列表项及其名称的所有组合 - Get all combinations of list items with their names Python:清单项目集的所有可能组合 - Python: all possible combinations of list items Set 如何使用另一个列表中的所有项目划分一个列表中的所有项目,并进行所有可能的组合? - How to divide all items in one list using all items in another list, and doing all possible combinations? 用python中所有可能组合的另一个列表替换一个项目列表 - Replace one list of items with another list in all possible combinations in python 您将如何递归获取列表中项目的所有组合 - How Would You Recursively Get All The Combinations Of Items Within A List 将 a 项的所有组合列出到 b 个大小为 c 的组中 - List all combinations of a items into b groups of size c 如何填充包含两个不同表中项目的所有可能组合的新 dataframe - How to populate a new dataframe containing all the possible combinations from items in two different tables 在数组数组中找到所有可能的项目组合 - Find all possible combinations of items in array of arrays 生成列表的所有有序组合,其中每个组合包括所有项目 - Generate all ordered combinations of a list, where each combination includes all items 鉴于两个项目不能在同一列表中,我如何获得列表的所有组合? - How can I get all the combinations of a list given that two items can not be in the same list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM