计算每个元素的排列数

Counting number of permutations of each element

我需要一些帮助。我查了一下,关于 'counting permutations' 的问题很少,但我没有找到适合我的情况的答案。

我想计算项目列表中每个项目的排列总数。比如说,你有两个列表('first','second' 见下文),对于 'first' 的每个元素,我想知道它的唯一排列总数。例如,对于 'first' 中的 'a',我们有

ab ac ad ab ac ad ab ab

通过删除重复项,我们有

ab ac ad

因此 'a' 的排列数将为 '3'

我想得到的最终结果应该是这样的

(a, 3)

(b, 3)

(c, 3)

(d, 3)

我从

开始
import itertools
from collections import Counter
first = ['a','b','c','d']
second = [['a','b','c','d'], ['a','b'], ['a','c','d'], ['a','b','d']]
c = Counter()
for let in second:
      letPermut = list(set(itertools.permutations(let, 2)))
      for i in first:
          for permut in letPermut:
                 if permut[0] == i:
                        c[i] += 1
      for item in c.items():
          print(item)

但是在输出中我得到了 first 列表中每个元素的不同计数,并且计数器的结果高于预期输出。我不知道我做错了什么。

有什么帮助吗?

嗯,问题还不是很清楚,但是我的0.02$:

def do_the_stuff(first, second):
    second = list(set(second))

    return {
        el1: sum(1 for el2 in second if el1 in el2)
        for el1 in first
    }

加上一些测试数据:

>>> first = ['a','b','c','d', 'j']
>>> second = ['abcd', 'ab', 'ab', 'acd', 'abd']
>>> print do_the_stuff(first, second)
{'a': 4, 'c': 2, 'b': 3, 'd': 3, 'j': 0}       

如果我确实理解你的问题,这些更改会使你的代码忽略重复排列:

import itertools
from collections import Counter
first = ['a','b','c','d']
second = [['a','b','c','d'], ['a','b'], ['a','c','d'], ['a','b','d']]
uniques = []
c = Counter()
for let in second:
    letPermut = list(set(itertools.permutations(let, 2)))
    for i in first:
        for permut in letPermut:
            if permut[0] == i and not permut in uniques:
                c[i] += 1
                uniques.append(permut)
for item in c.items():
    print(item)

变化:

  • 声明一个名为 uniques
  • 的空列表
  • 我们在计算 +1
  • 之前检查 uniques 排列是否重复
  • 增加计数器后,我们将排列添加到 uniques 以供将来检查
  • 将打印循环从 for let in second 循环中取出。因此,每个计数器最后只打印一次。