【问题标题】:Filtering a permutation [duplicate]过滤排列[重复]
【发布时间】:2015-12-13 22:01:40
【问题描述】:

我是一名初级程序员,在使用 Python 2.7 进行一些工作时,遇到了一个我似乎无法通过的问题。我试图找到所有数字对的所有排列;在一个有 4 位数字的数组中。示例:array = ["a", "b", "c", "d"] 我想看到这样的排列:ab, ac, ad, ba, cd, da... ect...到目前为止,这是我的代码,我无法弄清楚下一步:

from itertools import permutations
array = ["a", "b", "c", "d"]
for p in permutations(array):
    print(p)

如果能得到任何帮助,我将不胜感激,谢谢。

【问题讨论】:

  • 哪个让你感到困惑?如何获得长度为 2 的排列或如何将元组转回字符串或其他内容?

标签: python algorithm permutation


【解决方案1】:

指定可选参数r如:

from itertools import permutations
array = ["a", "b", "c", "d"]
for p in permutations(array, r=2):
    print(p)

【讨论】:

  • 非常感谢,这正是我想要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-18
  • 2012-12-12
  • 2018-03-21
  • 1970-01-01
  • 2021-12-07
  • 2018-06-13
  • 2013-08-15
相关资源
最近更新 更多