【问题标题】:Running through combinations of 4 numbers运行 4 个数字的组合
【发布时间】:2017-09-23 14:52:21
【问题描述】:

我需要一个代码来运行 4 个数字的可能组合,例如 1234 将产生 1234、1243、1324 等的 24 个组合。但不这样做 ['1', '12', '123', ect] 我希望它只有 4 个数字长度组合,(只是改变顺序)
一个很长的选择是

    import random

将 4 个数字中的一个随机化,再随机化另一个,然后检查该组合是否已打印或添加到包含可能组合的数组中,然后最终打印出所有组合。

array = ['1234', '1243', '1342', '1324' ect]


但这需要很长时间,而且效率很低。 编码很新:) 谢谢

【问题讨论】:

  • 也许这个问题会有所帮助:stackoverflow.com/questions/464864/…
  • @boroboris 我不希望它是 '1' '12' '123' 这会产生超过 24 种组合。将其添加到描述中。谢谢你的建议
  • @Mormin 嗨,我对此很陌生。你能解释一下我的问题有什么问题吗?谢谢

标签: python combinations options


【解决方案1】:

使用itertools.permutations()str.join()函数的解决方案:

import itertools

n = '1234'
a = [''.join(i) for i in itertools.permutations(n, 4)]

print(a)   # prints 24 permutations

输出:

['1234', '1243', '1324', '1342', '1423', '1432', '2134', '2143', '2314', '2341', '2413', '2431', '3124', '3142', '3214', '3241', '3412', '3421', '4123', '4132', '4213', '4231', '4312', '4321']

【讨论】:

  • 您在此处的list 呼叫不会添加任何内容。
  • @DSM,对,list 调用没有理由,它是在开始时调试(加入之前)。固定
【解决方案2】:

您可以在 python 中使用内置模块itertools。参考这个问题已经问过here

import itertools
array = itertools.permutations([1, 2, 3, 4])

for eachpermutation in array:
    print(eachpermutation )

应该给你这样的输出

(1, 2, 3, 4)
(1, 2, 4, 3)
(1, 3, 2, 4)
(1, 3, 4, 2)
(1, 4, 2, 3)
(1, 4, 3, 2)
(2, 1, 3, 4)
(2, 1, 4, 3)
(2, 3, 1, 4)
(2, 3, 4, 1)
(2, 4, 1, 3)
(2, 4, 3, 1)
(3, 1, 2, 4)
(3, 1, 4, 2)
(3, 2, 1, 4)
(3, 2, 4, 1)
(3, 4, 1, 2)
(3, 4, 2, 1)
(4, 1, 2, 3)
(4, 1, 3, 2)
(4, 2, 1, 3)
(4, 2, 3, 1)
(4, 3, 1, 2)
(4, 3, 2, 1)

如果需要将子列表串联成一个数字,可以使用here提供的答案

for eachpermutation in array:
    print(int(''.join(str(i) for i in eachpermutation )))

为您提供以下输出

1234
1243
1324
1342
1423
1432
2134
2143
2314
2341
2413
2431
3124
3142
3214
3241
3412
3421
4123
4132
4213
4231
4312
4321

希望有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    • 2018-11-14
    • 2021-07-02
    相关资源
    最近更新 更多