简体   繁体   English

如何计算python列表中的组合数量

[英]How to count amount of combinations in a python list

I need some help to count the amount of combinations in a list array in python.我需要一些帮助来计算 python 中列表数组中的组合数量。

I need to count the amount of possible combinations between three letters in all of the elements and then find the most repeated one.我需要计算所有元素中三个字母之间可能组合的数量,然后找到最重复的一个。 eg, ABC, CDA, CCA, etc...例如,ABC、CDA、CCA 等...

I have created a for loop to look in each element of the list, then I have another loop to check each combo of three letters and add it to a new list.我创建了一个for循环来查看列表的每个元素,然后我有另一个循环来检查三个字母的每个组合并将其添加到新列表中。 I am not sure about how to count the amount of times a combination is repeated, and then to find the mode, I think I might use the max() function.我不确定如何计算组合重复的次数,然后找到模式,我想我可能会使用 max() 函数。

this is part of the code I have, but it does not work as I am expecting, because it is just adding each item of the list into an independent list.这是我拥有的代码的一部分,但它不像我期望的那样工作,因为它只是将列表的每个项目添加到一个独立的列表中。

lst = ["ABCDABCD", "ABDCABD", "ACCACABB", "BACDABC"] 

for combo in lst:
   for i in range (0,3):      
      combolst = []
      combolst.append(lst[i].split())
      print(combolst)

I am new to coding so that's why I'm here.我是编码新手,所以这就是我在这里的原因。 Thanks!谢谢!

(Assuming my math memory isn't garbage) So okay, we are interested in combinations. (假设我的数学记忆不是垃圾)好吧,我们对组合感兴趣。 Your code simply splits the list and creates a new one (as you said).您的代码只是拆分列表并创建一个新列表(如您所说)。 Then we would use the combination formula : n!/(z!(nz)!).然后我们将使用组合公式:n!/(z!(nz)!)。 Where:在哪里:

  • n is the number of elements, in this case the length of our string in question n 是元素的数量,在这种情况下是我们所讨论的字符串的长度
  • z would be how many objects we wish to choose z 将是我们希望选择的对象数量

Thus you would get:因此你会得到:

for combo in lst:
    n = math.factorial(len(combo))
    r = math.factorial(3)
    nMinR = math.factorial((len(combo) - 3))
    result = n/(r*nMinR)
    print(result)

This is for combination, if we want permutations (where order does matter)这是用于组合,如果我们想要排列(顺序很重要)

for combo in lst:
        n = math.factorial(len(combo))
        nMinR = math.factorial((len(combo) - 3))
        result = n/(nMinR)
        print(result)

I hope I understood your question correctly.我希望我正确理解了你的问题。 Here is some reading about combinations vs permutations ( https://medium.com/i-math/combinations-permutations-fa7ac680f0ac ).这里有一些关于组合与排列的阅读( https://medium.com/i-math/combinations-permutations-fa7ac680f0ac )。 Keep in mind, the above code will only print out how many possible combinations or permutations are possible;请记住,上面的代码只会打印出有多少可能的组合或排列; it won't actually try to construct the possible values它实际上不会尝试构造可能的值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM