• 技术文章 >Python技术 >Python基础教程

    Python如何从列表中获取笛卡尔积

    小妮浅浅小妮浅浅2021-09-10 17:31:35原创2997

    1、可以使用itertools.product在标准库中使用以获取笛卡尔积。

    from itertools import product
     
    somelists = [
       [1, 2, 3],
       ['a', 'b'],
       [4, 5]
    ]
     
    result = list(product(*somelists))
    print(result)

    2、迭代方法。

    def cartesian_iterative(pools):
      result = [[]]
      for pool in pools:
        result = [x+[y] for x in result for y in pool]
      return result

    3、递归方法。

    def cartesian_recursive(pools):
      if len(pools) > 2:
        pools[0] = product(pools[0], pools[1])
        del pools[1]
        return cartesian_recursive(pools)
      else:
        pools[0] = product(pools[0], pools[1])
        del pools[1]
        return pools
    def product(x, y):
      return [xx + [yy] if isinstance(xx, list) else [xx] + [yy] for xx in x for yy in y]

    4、Lambda方法。

    def cartesian_reduct(pools):
      return reduce(lambda x,y: product(x,y) , pools)

    以上就是Python从列表中获取笛卡尔积的方法,希望对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python列表
    品易云
    上一篇:Python with as如何使用 下一篇:python如何检测pygame中的碰撞

    相关文章推荐

    • python列表有几种切片形式• python列表缓存的探究• python列表有哪些特点• python列表数据如何增加和删除• Python列表操作方法的整理• python列表元素的获取和查看• python列表清除元素的四种方式• python列表中if语句的用途• python列表如何分成大小均匀的块• python列表删除项目的方法• python列表有什么特点

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网