Python 3.x 从列表生成组合
我有以下代码: def produceCombinations(text, maximumWindowWidth) combinations = [] for windowWidth in range(1,maximumWindowWidth+1): for startingIndex in range(len(text)-windowWidth+1): combinations.append((text[startingIndex:startingIndex+windowWidth])) return combinations produceCombinations(("1","2","3","4","5","6",),3) def产品组合(文本、最大窗口宽度) 组合=[] 对于范围(1,最大windowWidth+1)内的windowWidth: 对于范围内的起始索引(长度(文本)-窗口宽度+1): compositions.append((文本[startingIndex:startingIndex+windowWidth])) 回报组合 产品组合((“1”、“2”、“3”、“4”、“5”、“6”)、3) 这将提供以下输出: ('1',) ('2',) ('3',) ('4',) ('5',) ('6',) ('1', '2') ('2', '3') ('3', '4') ('4', '5') ('5', '6') ('1', '2', '3') ('2', '3', '4') ('3', '4', '5') ('4', '5', '6') ('1',) ('2',) ('3',) ('4',) ('5',) ('6',) ('1', '2') ('2', '3') ('3', '4') ('4', '5') ('5', '6') ('1', '2', '3') ('2', '3', '4') ('3', '4', '5') ('4', '5', '6') 但是,我也希望该算法能为我提供额外的组合: ('1', '3') # hop of 1 ('2', '4') ('3', '5') ('4', '6') ('1', '4') # hop of 2 ('2', '5') ('3', '6') ('4', '7') ('1', '3', '4') # hop of 1 and 0 ('2', '4', '5') ('3', '5', '6') ('1', '2', '4') # hop of 0 and 1 ('2', '3', '5') ('3', '4', '6') ('1', '3', '5') # hop of 1 and 1 ('2', '4', '6') ('1', '2', '5') # hop of 0 and 2 ('2', '3', '6') ('1', '3', '6') # hop of 1 and 2 ('1', '4', '5') # hop of 2 and 0 ('2', '5', '6') ('1', '4', '6') # hop of 2 and 1 ('1','3')#1的跃点 ('2', '4') ('3', '5') ('4', '6') ('1','4')#第二跳 ('2', '5') ('3', '6') ('4', '7') ('1','3','4')#1和0的跃点 ('2', '4', '5') ('3', '5', '6') ('1','2','4')#0和1的跃点 ('2', '3', '5') ('3', '4', '6') ('1','3','5')#1和1的跳跃 ('2', '4', '6') ('1','2','5')#0和2的跃点 ('2', '3', '6') ('1','3','6')#1和2的跳跃 ('1','4','5')#2和0的跃点 ('2', '5', '6') ('1','4','6')#2和1的跳跃 其中,我的函数将有一个名为maximumHop的新参数,以限制这些额外组合的数量。对于上述示例,最大跳数为2,因为组合('1','5')是不可能的 有什么好的建议吗 谢谢 巴里使用itertools 看Python 3.x 从列表生成组合,python-3.x,Python 3.x,我有以下代码: def produceCombinations(text, maximumWindowWidth) combinations = [] for windowWidth in range(1,maximumWindowWidth+1): for startingIndex in range(len(text)-windowWidth+1): combinations.append((text[startingIndex:startingIndex+w