第1步 :我发现想将列表分成几类的最简单方法是尝试获得分割位置的组合。这是一个实现:
def split_list(data, n): from itertools import combinations, chain for splits in combinations(range(1, len(data)), n-1): result = [] prev = None for split in chain(splits, [None]): result.append(data[prev:split]) prev = split yield result>>> list(split_list([1, 2, 3, 4], 2))[[[1], [2, 3, 4]], [[1, 2], [3, 4]], [[1, 2, 3], [4]]]>>> list(split_list([1, 2, 3, 4], 3))[[[1], [2], [3, 4]], [[1], [2, 3], [4]], [[1, 2], [3], [4]]]
第2步 :首先,你需要转换就像一个列表
[[1], [2, 3, 4]],一个像
[1, 234]。您可以使用以下功能执行此操作:
def list_to_int(data): result = 0 for i, v in enumerate(reversed(data)): result += 10**i * v return result>>> map(list_to_int, [[1], [2, 3], [4, 5, 6]])[1, 23, 456]
现在,您可以使用
reduce()以下命令在结果列表上执行操作:
>>> import operator>>> reduce(operator.add, [1, 23, 456]) # or int.__add__ instead of operator.add480
完整的解决方案: 基于不同操作员的编辑引用需求:
def op_iter_reduce(ops, values): op_dict = {'+': int.__add__, '-': int.__sub__, '*': int.__mul__, '/': int.__div__} op_iter = lambda a, (i, b): op_dict[ops[i]](a, b) return reduce(op_iter, enumerate(values[1:]), values[0])def group_and_map(data, num_groups): from itertools import combinations_with_replacement op_dict = {'+': int.__add__, '-': int.__sub__, '*': int.__mul__, '/': int.__div__} template = ['']*(num_groups*2 - 1) + ['=', ''] op_iter = lambda a, (i, b): op_dict[ops[i]](a, b) for groups in split_list(data, num_groups): ints = map(list_to_int, groups) template[:-2:2] = map(str, ints) for ops in combinations_with_replacement('+-*/', num_groups-1): template[1:-2:2] = ops template[-1] = str(op_iter_reduce(ops, ints)) print ' '.join(template)>>> group_and_map([1, 2, 3, 4], 2)1 + 234 = 2351 - 234 = -2331 * 234 = 2341 / 234 = 012 + 34 = 4612 - 34 = -2212 * 34 = 40812 / 34 = 0123 + 4 = 127123 - 4 = 119123 * 4 = 492123 / 4 = 30如果您使用的是Python
2.6或更低版本,
itertools.combinations_with_replacement()并且不可用,则可以使用此处链接的配方。



