栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

仅给出子列表的数量(长度可变),显示列表的所有可能分组

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

仅给出子列表的数量(长度可变),显示列表的所有可能分组

第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()
并且不可用,则可以使用此处链接的配方。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/624846.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号