如何计算列表中重复项的出现和数量?

时间:2018-12-11 22:41:53

标签: python

我正在尝试计算列表中字符串的重复字符;另外,我根据变量是重复2还是3次来递增变量。

但是,在我的250个字符串测试列表中,它返回的总数为641,所以我确定有什么问题。

这是我的代码:

def findDupesNum(listy):
    a = []      # the current string's character list
    b = 0       # the 2-dupe counter
    c = 0       # the 3-dupe counter
    for i in listy:
        a.clear()
        for x in i:
            if x in a and a.count(x) == 1 and x != '':
                b += 1
            elif x in a and a.count(x) == 2 and x != '':
                c += 1
                b -= 1
            a.append(x)
        print('b = ' + str(b) + ' and c = ' + str(c))

3 个答案:

答案 0 :(得分:2)

使用字典来计算出现次数会容易一些:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale =1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Wordpress first site</title>
    <!-- ==================== BOOTSTRAP CSS ==================== -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

    <!-- ==================== FONTAWESOME ICONS ==================== -->
    <link rel="stylesheet" href="vendors/css/fontawesome/css/fontawesome.min.css">
    <!-- ==================== GOOGLE FONTS ==================== -->
    <link href="https://fonts.googleapis.com/css?family=Lato:300,300i,400,700,700i" rel="stylesheet">

    <!-- HTML5 shiv and Respond.js IE8 support of HTML5 elements and media queries -->

    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->

</head>
<body>
<!-- ==================== HEADER ==================== -->
<header>
    <div class="container" role="navigation">
        <nav class="navbar navbar-expand-lg navbar-light bg-light" style="position:relative">
          
            
            <a class="navbar-brand" href="#">Navbar</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            
            <div class="collapse navbar-collapse" id="navbarSupportedContent" style="position:absolute;right:10px;">
                <ul class="navbar-nav mr-auto d-flex justify-content-end">
                    <li class="nav-item active">
                        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">Link</a>
                    </li>
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            Dropdown
                        </a>
                        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                            <a class="dropdown-item" href="#">Action</a>
                            <a class="dropdown-item" href="#">Another action</a>
                            <div class="dropdown-divider"></div>
                            <a class="dropdown-item" href="#">Something else here</a>
                        </div>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link disabled" href="#">Disabled</a>
                    </li>
                </ul>

            </div>
          

答案 1 :(得分:2)

这似乎是documentationdict的子类)的一个好用例。

from collections import Counter

def find_duplicates(string_list):
    total_counter = Counter()

    for s in string_list:
        s_counter = Counter(s)
        total_counter.update(s_counter)    # also update total counter

        print()
        print('this string:', s)
        print(
            'number of chars that appear 2 times in this string:',
            len([c for c, n in s_counter.items() if n == 2]))
        print(
            'number of chars that appear 3 times in this string:',
            len([c for c, n in s_counter.items() if n == 3]))

    # print()
    # print(
    #     'number of chars that appear 2 times in ALL strings:',
    #     len([c for c, n in total_counter.items() if n == 2]))
    # print(
    #     'number of chars that appear 3 times in ALL strings:',
    #     len([c for c, n in total_counter.items() if n == 3]))

输出看起来像这样:

>>> s_list = ['alfa', 'beta', 'gamma', 'aaabbcc']
>>> find_duplicates(s_list)

this string: alfa
number of chars that appear 2 times in this string: 1
number of chars that appear 3 times in this string: 0

this string: beta
number of chars that appear 2 times in this string: 0
number of chars that appear 3 times in this string: 0

this string: gamma
number of chars that appear 2 times in this string: 2
number of chars that appear 3 times in this string: 0

this string: aaabbcc
number of chars that appear 2 times in this string: 2
number of chars that appear 3 times in this string: 1

答案 2 :(得分:0)

这应该有效:

l = ["bob",'bob', "thomas", "rémi", "marc", 'rémi']

dictElt = {}

for string in l:
    if string in dictElt.keys(): #if the key of the dictionnary exists
        dictElt[string] += 1
    else:
        dictElt[string] = 1

print(dictElt)
# to get your results 
for string, nbr in dictElt.items():
    if nbr == 1:
         print(string, "number of occurences =", nbr)
    elif nbr ==2:
         print(string, "number of occurences =",nbr)
    elif nbr == 3:
         print(string, "number of occurences =",nbr)