python - 打印所有两位数字组合且某些数字不重复的程序
问题描述
有人可以告诉我如何创建一个快速的 python 程序来打印所有可能的两位数字组合:1、2 和 3。没有重复,所以没有 11、22 或 33。
解决方案
您可以将列表理解与条件一起使用(以排除相同的数字情况)。
digits = [1, 2, 3]
output = [(x, y) for x in digits for y in digits if x != y]
print(output)
# [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
一种更通用、更方便的方法(由 Chris 建议)是使用itertools.permutation
:
import itertools
output = list(itertools.permutations([1, 2, 3], 2))
推荐阅读
- php - PhpSpreadsheet laravel setCellValue vlookup 不起作用
- javascript - 返回(派遣)什么都不做
- amazon-kms - 如果通过 AD 激活 KMS 激活计数不会更新
- excel - 带有 VBA 的 Excel 中的多种语言日期格式
- jekyll - 用于为 Staticman 评论加载 _data 子文件夹的 Jekyll 液体语法?
- html - 如何水平放置表格(连续)?
- python - 无法从其他文件夹导入模块
- javascript - 将数组元素转换为父子元素
- azure - 用于监控 azure bot 框架项目中的运行状况的 Azure 应用洞察警报
- git - git中可能的文件夹结构?