【问题标题】:Python3 permutations with tuples that contain duplicates包含重复项的元组的 Python3 排列
【发布时间】:2017-11-01 21:08:48
【问题描述】:

我想创建具有重复元素的元组的所有可能组合。

例如,假设我们有 {3,3,0}。 我希望代码返回: (3,3,0) (3,0,3) (0,3,3)

我查看了 itertools 文档和许多堆栈溢出问题,但我没有找到答案。

我该如何实现它?或者,这可以普遍实现吗?

【问题讨论】:

  • {3,3,0} 是您的实际符号,它是 set?
  • from sympy.utilities.iterables import multiset_permutations 例如,list(multiset_permutations([3,3,0])) 给出[[0, 3, 3], [3, 0, 3], [3, 3, 0]]
  • 是的,这是一个集合,虽然 python 使它成为 {3,0}。
  • @BillBell 我不想在这个项目中添加另一个包,但是谢谢。
  • 请注意,您接受的内容会比较慢。

标签: python-3.x duplicates combinations itertools


【解决方案1】:

您可以使用 itertools 中的 permutations,然后使用 set 删除任何双精度:

result = set(permutations((3, 3, 0)))

【讨论】:

【解决方案2】:

使用第三方库more_itertools:

> pip install more_itertools

代码

import more_itertools as mit


iterable = (3, 3, 0)
list(mit.distinct_permutations(iterable))
# [(3, 3, 0), (3, 0, 3), (0, 3, 3)]

详情请见more_itertools docs。

【讨论】:

  • :) 你只能接受一个。 @Mureinik 的回答是 pythonic 并且完全可以接受。这个可能会快一点。
猜你喜欢
  • 1970-01-01
  • 2019-03-15
  • 1970-01-01
  • 1970-01-01
  • 2020-10-31
  • 1970-01-01
  • 2016-04-27
  • 1970-01-01
  • 2016-10-02
相关资源
最近更新 更多