python - 创建特定排列 Python
问题描述
我有一个二维列表的值:
# 4 x 4, 2-dimensional list
values = [[4, 7, 8],
[1, 3, 4],
[7, 5, 6],
[2, 9, 1]]
我想为每个列表创建包含这些值(笛卡尔积)的所有可能排列的元组。
# example for the list at index 0 of values
args0 = [(4, 7, 8), (7, 4, 8), (4, 8, 7), (8, 4, 7), (7, 8, 4), (8, 7, 4)]
有没有简单的方法来解决这个问题?我已经尝试过 itertools 但无法让它与“特定值”一起使用。
解决方案
您想要的是列表中每个元素的排列,所以只需map
itertools.permutations
:
import itertools
values = [[4, 7, 8],
[1, 3, 4],
[7, 5, 6],
[2, 9, 1]]
perms = map(itertools.permutations, values)
for v in perms:
print(list(v))
结果:
[(4, 7, 8), (4, 8, 7), (7, 4, 8), (7, 8, 4), (8, 4, 7), (8, 7, 4)]
[(1, 3, 4), (1, 4, 3), (3, 1, 4), (3, 4, 1), (4, 1, 3), (4, 3, 1)]
[(7, 5, 6), (7, 6, 5), (5, 7, 6), (5, 6, 7), (6, 7, 5), (6, 5, 7)]
[(2, 9, 1), (2, 1, 9), (9, 2, 1), (9, 1, 2), (1, 2, 9), (1, 9, 2)]
这里有一个活生生的例子
推荐阅读
- ios - 键盘与输入表单重叠,它不会在 ionic IOS 中向上滑动
- reactjs - React JS:如何确定你是在运行调试还是生产
- python - 立即从 cmd 获取结果,无需等待执行 python 脚本结束
- php - 数学类型工具栏未正确显示
- apache-kafka - 在 Kafka Confluent Cloud 中管理配额
- javascript - 计算日期范围内的余额 - PouchDB
- android - 是否可以将小部件添加到 cordova 应用程序?
- bash - Dockerfile | => 错误 [base 2/7] 运行 apt-get update -y && apt-get -y --no-install-recommends install curl wget && rm -rf /var/lib/apt/lists/*
- r - 如何在 R Shiny 中激活前 4 个操作的撤消按钮
- javascript - 如何通过单击列标题创建弹出框以对表格进行排序