zoukankan      html  css  js  c++  java
  • python 坐标遍历 生成笛卡尔积矩阵

    1. 主要场景

    • 生成两个列表的组合。
    • 生成坐标

    2. 函数

    用的是python itertools库的product函数,它返回一个生成器,生成元组。

    这个函数主要有两种用法,一种用法是对两个可遍历对象进行组合,如两个列表:

    from itertools import product
    A = [1,2,3]
    B = ["a", "b", "c"]
    for item in product(A, B):
        print(item)

    输出:

    (1, 'a')
    (1, 'b')
    (1, 'c')
    (2, 'a')
    (2, 'b')
    (2, 'c')
    (3, 'a')
    (3, 'b')
    (3, 'c')

    这种情况等价于:

    ((x,y) for x in A for y in B)

    另外一种用法是对本身进行生成,如我有一个边长为4*4的矩形,想生成所有坐标:

    from itertools import product
    for item in product(range(4), repeat=2):
        print(item)

    输出:

    (0, 0)
    (0, 1)
    (0, 2)
    (0, 3)
    (1, 0)
    (1, 1)
    (1, 2)
    (1, 3)
    (2, 0)
    (2, 1)
    (2, 2)
    (2, 3)
    (3, 0)
    (3, 1)
    (3, 2)
    (3, 3)

    其中repeat参数指示你生成的目标的维度,以上面为例,如果生成的是3维的坐标,则指定repeat=3即可。

    3. 参考

    https://docs.python.org/3/library/itertools.html

    (完)

    本文版权归作者(https://www.cnblogs.com/harrymore/)和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,如有问题, 可邮件(harrymore@126.com)咨询.
  • 相关阅读:
    .net core2.2
    9_山寨系统调用 SystemCallEntry
    7_API调用
    8_InlineHook
    6_再次开中断STI的正确姿势
    5_中断现场下
    4_中断现场中
    3_中断现场上
    2_多核复杂性
    1_中断提权
  • 原文地址:https://www.cnblogs.com/harrymore/p/15029596.html
Copyright © 2011-2022 走看看