如何用Python计算列表笛卡尔积?实现NFT项目资产全组合生成
Python 实现多属性笛卡尔积计算(NFT资产生成场景)
Python 内置的 itertools.product 方法专门用于计算可迭代对象的笛卡尔积,完美适配多类NFT属性组合的场景,不需要手写嵌套循环,支持任意数量的属性列表输入,运行效率远高于自定义遍历逻辑。
可直接运行的示例脚本
以下代码模拟了4类各10种的NFT属性,最终刚好生成 101010*10=10000 种唯一组合,符合你提到的Cryptokitties类资产生成需求:
import itertools # 模拟NFT各类属性列表,可按需扩展属性种类和每个类的取值 eye_shapes = [f"眼睛样式{i}" for i in range(1, 11)] skin_colors = [f"肤色{i}" for i in range(1, 11)] backgrounds = [f"背景样式{i}" for i in range(1, 11)] mouth_shapes = [f"嘴型{i}" for i in range(1, 11)] # 把所有属性列表统一放入集合 attribute_lists = [eye_shapes, skin_colors, backgrounds, mouth_shapes] # 计算笛卡尔积,得到所有唯一组合 all_combinations = list(itertools.product(*attribute_lists)) # 验证结果数量,4类各10种的场景下输出为10000 print(f"总组合数:{len(all_combinations)}") # 打印前3组示例,确认组合格式 for idx, combo in enumerate(all_combinations[:3], 1): print(f"第{idx}组组合:眼睛={combo[0]}, 肤色={combo[1]}, 背景={combo[2]}, 嘴型={combo[3]}") # 如需转成字典格式方便后续生成元数据、存储数据库,可按如下处理 formatted_combinations = [] for combo in all_combinations: formatted_combinations.append({ "eye_shape": combo[0], "skin_color": combo[1], "background": combo[2], "mouth_shape": combo[3] })
注意事项
- 若属性组合量级极大(超过10万组),不要直接转成list占用内存,可直接遍历
itertools.product返回的迭代器,边遍历边处理数据 - 若需要排除特定非法组合,在遍历过程中加过滤条件即可
- 可根据业务需求增减
attribute_lists里的属性列表,不管有多少类属性,itertools.product都可正常处理
内容的提问来源于stack exchange,提问作者Jordan102
相关产品推荐
相关产品推荐

