简体   繁体   English

如何计算列表项的出现次数?

[英]How do I count the occurrences of a list item?

Given a single item, how do I count occurrences of it in a list, in Python?给定一个项目,我如何计算它在列表中的出现次数,在 Python 中?


A related but different problem is counting occurrences of each different element in a collection, getting a dictionary or list as a histogram result instead of a single integer. For that problem, see Using a dictionary to count the items in a list .一个相关但不同的问题是计算集合中每个不同元素的出现次数,获取字典或列表作为直方图结果而不是单个 integer。对于该问题,请参阅使用字典计算列表中的项目

If you only want one item's count, use the count<\/code> method:如果您只想要一项的计数,请使用count<\/code>方法:

>>> [1, 2, 3, 4, 1, 4, 1].count(1)
3

Use Counter<\/code><\/a> if you are using Python 2.7 or 3.x and you want the number of occurrences for each element:如果您使用的是 Python 2.7 或 3.x 并且想要每个元素的出现次数,请使用Counter<\/code><\/a> :

>>> from collections import Counter
>>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
>>> Counter(z)
Counter({'blue': 3, 'red': 2, 'yellow': 1})

Counting the occurrences of one item in a list<\/strong>计算列表中一项的出现次数<\/strong>

For counting the occurrences of just one list item you can use count()<\/code>要计算仅一个列表项的出现次数,您可以使用count()<\/code>

>>> l = ["a","b","b"]
>>> l.count("a")
1
>>> l.count("b")
2

在字典中获取每个项目出现次数的另一种方法:

dict((i, a.count(i)) for i in a)

Given an item, how can I count its occurrences in a list in Python?给定一个项目,我如何计算它在 Python 列表中的出现次数?

Here's an example list:这是一个示例列表:

>>> l = list('aaaaabbbbcccdde')
>>> l
['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'e']

list.count

There's the list.count methodlist.count方法

>>> l.count('b')
4

This works fine for any list.这适用于任何列表。 Tuples have this method as well:元组也有这种方法:

>>> t = tuple('aabbbffffff')
>>> t
('a', 'a', 'b', 'b', 'b', 'f', 'f', 'f', 'f', 'f', 'f')
>>> t.count('f')
6

collections.Counter

And then there's collections.Counter.然后是 collections.Counter。 You can dump any iterable into a Counter, not just a list, and the Counter will retain a data structure of the counts of the elements.您可以将任何可迭代对象转储到 Counter 中,而不仅仅是列表,并且 Counter 将保留元素计数的数据结构。

Usage:用法:

>>> from collections import Counter
>>> c = Counter(l)
>>> c['b']
4

Counters are based on Python dictionaries, their keys are the elements, so the keys need to be hashable.计数器基于 Python 字典,它们的键是元素,因此键需要是可散列的。 They are basically like sets that allow redundant elements into them.它们基本上就像允许冗余元素进入它们的集合。

Further usage of collections.Counter collections.Counter的进一步使用

You can add or subtract with iterables from your counter:您可以使用计数器中的可迭代对象添加或减去:

>>> c.update(list('bbb'))
>>> c['b']
7
>>> c.subtract(list('bbb'))
>>> c['b']
4

And you can do multi-set operations with the counter as well:您还可以使用计数器进行多组操作:

>>> c2 = Counter(list('aabbxyz'))
>>> c - c2                   # set difference
Counter({'a': 3, 'c': 3, 'b': 2, 'd': 2, 'e': 1})
>>> c + c2                   # addition of all elements
Counter({'a': 7, 'b': 6, 'c': 3, 'd': 2, 'e': 1, 'y': 1, 'x': 1, 'z': 1})
>>> c | c2                   # set union
Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1, 'y': 1, 'x': 1, 'z': 1})
>>> c & c2                   # set intersection
Counter({'a': 2, 'b': 2})

Why not pandas?为什么不是熊猫?

Another answer suggests:另一个答案表明:

Why not use pandas?为什么不使用熊猫?

Pandas is a common library, but it's not in the standard library. Pandas 是一个通用库,但它不在标准库中。 Adding it as a requirement is non-trivial.将其添加为要求并非易事。

There are builtin solutions for this use-case in the list object itself as well as in the standard library.列表对象本身以及标准库中都有针对此用例的内置解决方案。

If your project does not already require pandas, it would be foolish to make it a requirement just for this functionality.如果您的项目还不需要 pandas,那么仅仅为此功能要求它是愚蠢的。

list.count(x) returns the number of times x appears in a list list.count(x)返回x在列表中出现的次数

see: http://docs.python.org/tutorial/datastructures.html#more-on-lists见: http ://docs.python.org/tutorial/datastructures.html#more-on-lists

I've compared all suggested solutions (and a few new ones) with perfplot<\/a> (a small project of mine).我已经将所有建议的解决方案(以及一些新的解决方案)与perfplot<\/a> (我的一个小项目)进行了比较。

Counting one<\/em> item计数一项<\/em><\/h3>

For large enough arrays, it turns out that对于足够大的数组,事实证明

numpy.sum(numpy.array(a) == 1)<\/code><\/pre>

is slightly faster than the other solutions.比其他解决方案略快。

在此处输入图像描述<\/a>

Counting all<\/em> items计算所有<\/em>项目<\/h3>

As established before<\/a> ,如前所述<\/a>,

 numpy.bincount(a)<\/code><\/pre>

is what you want.是你想要的。

在此处输入图像描述<\/a>


Code to reproduce the plots:重现绘图的代码:

 from collections import Counter from collections import defaultdict import numpy import operator import pandas import perfplot def counter(a): return Counter(a) def count(a): return dict((i, a.count(i)) for i in set(a)) def bincount(a): return numpy.bincount(a) def pandas_value_counts(a): return pandas.Series(a).value_counts() def occur_dict(a): d = {} for i in a: if i in d: d[i] = d[i]+1 else: d[i] = 1 return d def count_unsorted_list_items(items): counts = defaultdict(int) for item in items: counts[item] += 1 return dict(counts) def operator_countof(a): return dict((i, operator.countOf(a, i)) for i in set(a)) perfplot.show( setup=lambda n: list(numpy.random.randint(0, 100, n)), n_range=[2**k for k in range(20)], kernels=[ counter, count, bincount, pandas_value_counts, occur_dict, count_unsorted_list_items, operator_countof ], equality_check=None, logx=True, logy=True, )<\/code><\/pre> 
                  
  1. <\/li><\/ol>
     from collections import Counter from collections import defaultdict import numpy import operator import pandas import perfplot def counter(a): return Counter(a) def count(a): return dict((i, a.count(i)) for i in set(a)) def bincount(a): return numpy.bincount(a) def pandas_value_counts(a): return pandas.Series(a).value_counts() def occur_dict(a): d = {} for i in a: if i in d: d[i] = d[i] + 1 else: d[i] = 1 return d def count_unsorted_list_items(items): counts = defaultdict(int) for item in items: counts[item] += 1 return dict(counts) def operator_countof(a): return dict((i, operator.countOf(a, i)) for i in set(a)) b = perfplot.bench( setup=lambda n: list(numpy.random.randint(0, 100, n)), n_range=[2 ** k for k in range(20)], kernels=[ counter, count, bincount, pandas_value_counts, occur_dict, count_unsorted_list_items, operator_countof, ], equality_check=None, ) b.save("out.png") b.show()<\/code><\/pre>"

If you want to count all values at once<\/strong> you can do it very fast using numpy arrays and bincount<\/code> as follows如果您想一次计算所有值,<\/strong>您可以使用 numpy 数组和bincount<\/code>快速完成,如下所示

import numpy as np
a = np.array([1, 2, 3, 4, 1, 4, 1])
np.bincount(a)

If you can use pandas<\/code> , then value_counts<\/code> is there for rescue.如果您可以使用pandas<\/code> ,那么value_counts<\/code>就可以进行救援。

>>> import pandas as pd
>>> a = [1, 2, 3, 4, 1, 4, 1]
>>> pd.Series(a).value_counts()
1    3
4    2
3    1
2    1
dtype: int64

Why not using Pandas?为什么不使用熊猫?

import pandas as pd

my_list = ['a', 'b', 'c', 'd', 'a', 'd', 'a']

# converting the list to a Series and counting the values
my_count = pd.Series(my_list).value_counts()
my_count

I had this problem today and rolled my own solution before I thought to check SO.我今天遇到了这个问题,并在我想检查 SO 之前推出了自己的解决方案。 This:这:

dict((i,a.count(i)) for i in a)

Count of all elements with itertools.groupby()<\/code>使用itertools.groupby()<\/code>计算所有元素<\/h2>

Antoher possiblity for getting the count of all elements in the list could be by means of itertools.groupby()<\/code> .获取列表中所有元素的计数的另一种可能性是通过itertools.groupby()<\/code> 。

With "duplicate" counts<\/strong>带有“重复”计数<\/strong>

from itertools import groupby L = ['a', 'a', 'a', 't', 'q', 'a', 'd', 'a', 'd', 'c'] # Input list counts = [(i, len(list(c))) for i,c in groupby(L)] # Create value-count pairs as list of tuples print(counts)<\/code><\/pre>

Returns退货

[('a', 3), ('t', 1), ('q', 1), ('a', 1), ('d', 1), ('a', 1), ('d', 1), ('c', 1)]<\/code><\/pre>

Notice how it combined the first three a<\/code> 's as the first group, while other groups of a<\/code> are present further down the list.请注意它如何将前三个a<\/code>组合为第一组,而a<\/code>的其他组则出现在列表的下方。 This happens because the input list L<\/code> was not sorted.发生这种情况是因为输入列表L<\/code>未排序。 This can be a benefit sometimes if the groups should in fact be separate.如果这些组实际上应该是分开的,这有时可能是一个好处。

With unique counts<\/strong>具有独特的计数<\/strong>

If unique group counts are desired, just sort the input list:如果需要唯一组计数,只需对输入列表进行排序:

 counts = [(i, len(list(c))) for i,c in groupby(sorted(L))] print(counts)<\/code><\/pre>

Returns退货

[('a', 5), ('c', 1), ('d', 2), ('q', 1), ('t', 1)]<\/code><\/pre>

Note:<\/strong> For creating unique counts, many of the other answers provide easier and more readable code compared to the groupby<\/code> solution.注意:<\/strong>为了创建唯一计数,与groupby<\/code>解决方案相比,许多其他答案提供了更简单、更易读的代码。 But it is shown here to draw a parallel to the duplicate count example.但这里显示的是与重复计数示例平行。

"

Below are the three solutions:以下是三种解决方案:

Fastest is using a for loop and storing it in a Dict.最快的是使用 for 循环并将其存储在字典中。

import time
from collections import Counter


def countElement(a):
    g = {}
    for i in a:
        if i in g: 
            g[i] +=1
        else: 
            g[i] =1
    return g


z = [1,1,1,1,2,2,2,2,3,3,4,5,5,234,23,3,12,3,123,12,31,23,13,2,4,23,42,42,34,234,23,42,34,23,423,42,34,23,423,4,234,23,42,34,23,4,23,423,4,23,4]


#Solution 1 - Faster
st = time.monotonic()
for i in range(1000000):
    b = countElement(z)
et = time.monotonic()
print(b)
print('Simple for loop and storing it in dict - Duration: {}'.format(et - st))

#Solution 2 - Fast
st = time.monotonic()
for i in range(1000000):
    a = Counter(z)
et = time.monotonic()
print (a)
print('Using collections.Counter - Duration: {}'.format(et - st))

#Solution 3 - Slow
st = time.monotonic()
for i in range(1000000):
    g = dict([(i, z.count(i)) for i in set(z)])
et = time.monotonic()
print(g)
print('Using list comprehension - Duration: {}'.format(et - st))

Result结果

#Solution 1 - Faster
{1: 4, 2: 5, 3: 4, 4: 6, 5: 2, 234: 3, 23: 10, 12: 2, 123: 1, 31: 1, 13: 1, 42: 5, 34: 4, 423: 3}
Simple for loop and storing it in dict - Duration: 12.032000000000153
 #Solution 2 - Fast
Counter({23: 10, 4: 6, 2: 5, 42: 5, 1: 4, 3: 4, 34: 4, 234: 3, 423: 3, 5: 2, 12: 2, 123: 1, 31: 1, 13: 1})
Using collections.Counter - Duration: 15.889999999999418
 #Solution 3 - Slow
{1: 4, 2: 5, 3: 4, 4: 6, 5: 2, 34: 4, 423: 3, 234: 3, 42: 5, 12: 2, 13: 1, 23: 10, 123: 1, 31: 1}
Using list comprehension - Duration: 33.0

Although it is very old question, since i didn't find a one liner, i made one.虽然这是一个很老的问题,但由于我没有找到一个班轮,所以我做了一个。

# original numbers in list
l = [1, 2, 2, 3, 3, 3, 4]

# empty dictionary to hold pair of number and its count
d = {}

# loop through all elements and store count
[ d.update( {i:d.get(i, 0)+1} ) for i in l ]

print(d)
# {1: 1, 2: 2, 3: 3, 4: 1}
# Python >= 2.6 (defaultdict) && < 2.7 (Counter, OrderedDict)
from collections import defaultdict
def count_unsorted_list_items(items):
    """
    :param items: iterable of hashable items to count
    :type items: iterable

    :returns: dict of counts like Py2.7 Counter
    :rtype: dict
    """
    counts = defaultdict(int)
    for item in items:
        counts[item] += 1
    return dict(counts)


# Python >= 2.2 (generators)
def count_sorted_list_items(items):
    """
    :param items: sorted iterable of items to count
    :type items: sorted iterable

    :returns: generator of (item, count) tuples
    :rtype: generator
    """
    if not items:
        return
    elif len(items) == 1:
        yield (items[0], 1)
        return
    prev_item = items[0]
    count = 1
    for item in items[1:]:
        if prev_item == item:
            count += 1
        else:
            yield (prev_item, count)
            count = 1
            prev_item = item
    yield (item, count)
    return


import unittest
class TestListCounters(unittest.TestCase):
    def test_count_unsorted_list_items(self):
        D = (
            ([], []),
            ([2], [(2,1)]),
            ([2,2], [(2,2)]),
            ([2,2,2,2,3,3,5,5], [(2,4), (3,2), (5,2)]),
            )
        for inp, exp_outp in D:
            counts = count_unsorted_list_items(inp) 
            print inp, exp_outp, counts
            self.assertEqual(counts, dict( exp_outp ))

        inp, exp_outp = UNSORTED_WIN = ([2,2,4,2], [(2,3), (4,1)])
        self.assertEqual(dict( exp_outp ), count_unsorted_list_items(inp) )


    def test_count_sorted_list_items(self):
        D = (
            ([], []),
            ([2], [(2,1)]),
            ([2,2], [(2,2)]),
            ([2,2,2,2,3,3,5,5], [(2,4), (3,2), (5,2)]),
            )
        for inp, exp_outp in D:
            counts = list( count_sorted_list_items(inp) )
            print inp, exp_outp, counts
            self.assertEqual(counts, exp_outp)

        inp, exp_outp = UNSORTED_FAIL = ([2,2,4,2], [(2,3), (4,1)])
        self.assertEqual(exp_outp, list( count_sorted_list_items(inp) ))
        # ... [(2,2), (4,1), (2,1)]

To count the number of diverse elements having a common type:计算具有共同类型的不同元素的数量:

li = ['A0','c5','A8','A2','A5','c2','A3','A9']

print sum(1 for el in li if el[0]=='A' and el[1] in '01234')

I would use filter()<\/code> , take Lukasz's example:我会使用filter()<\/code> ,以 Lukasz 为例:

>>> lst = [1, 2, 3, 4, 1, 4, 1]
>>> len(filter(lambda x: x==1, lst))
3

use %timeit to see which operation is more efficient.使用 %timeit 查看哪个操作更有效。 np.array counting operations should be faster. np.array 计数操作应该更快。

 from collections import Counter
 mylist = [1,7,7,7,3,9,9,9,7,9,10,0] 
 types_counts=Counter(mylist)
 print(types_counts)

May not be the most efficient, requires an extra pass to remove duplicates.可能不是最有效的,需要额外通过才能删除重复项。

Functional implementation :功能实现:

arr = np.array(['a','a','b','b','b','c'])
print(set(map(lambda x  : (x , list(arr).count(x)) , arr)))

Given a list X给定一个列表 X

 import numpy as np
 X = [1, -1, 1, -1, 1]
sum([1 for elem in <yourlist> if elem==<your_value>])

这将返回 your_value 的出现次数

Alternatively, you can also implement the counter by yourself.或者,您也可以自己实现计数器。 This is the way I do:这就是我的做法:

item_list = ['me', 'me', 'you', 'you', 'you', 'they']

occ_dict = {}

for item in item_list:
    if item not in occ_dict:
        occ_dict[item] = 1
    else:
        occ_dict[item] +=1

print(occ_dict)

if you want a number of occurrences for the particular element:如果您想要特定元素的多次出现:

>>> from collections import Counter
>>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
>>> single_occurrences = Counter(z)
>>> print(single_occurrences.get("blue"))
3
>>> print(single_occurrences.values())
dict_values([3, 2, 1])
l2=[1,"feto",["feto",1,["feto"]],['feto',[1,2,3,['feto']]]]
count=0
 def Test(l):   
        global count 
        if len(l)==0:
             return count
        count=l.count("feto")
        for i in l:
             if type(i) is list:
                count+=Test(i)
        return count   
    print(Test(l2))
mot = ["compte", "france", "zied"]
lst = ["compte", "france", "france", "france", "france"]
dict((x, lst.count(x)) for x in set(mot))

For this topic I know the below six ways by which you can count the number of occurrences of the element in the list:对于本主题,我知道以下六种方法可以计算列表中元素的出现次数:

1) Using count() method 1) 使用count()方法

count() is the in-built function by which python count occurrences in list. count()是内置的 function ,通过它 python 在列表中计数出现。 It is the easiest among all other methods used to count the occurrence.在所有其他用于计算发生次数的方法中,它是最简单的。 Count() methods take one argument, ie, the element for which the number of occurrences is to be counted. Count()方法采用一个参数,即要计算其出现次数的元素。

For example:例如:

sample_list = ["a", "ab", "a", "abc", "ab", "ab"]
print(sample_list.count("a"))
print(sample_list.count("ab"))

Output Output

 2 3

2) Using a loop 2)使用循环

Another simple approach to counting the occurrence is by using a loop with the counter variable.另一种计算发生次数的简单方法是使用带有计数器变量的循环。 Here, the counter variable keeps increasing its value by one each time after traversing through the given element.在这里,计数器变量在遍历给定元素后每次都会将其值增加一。 At last, the value of the counter variable displays the number of occurrences of the element.最后,计数器变量的值显示元素出现的次数。

For example:例如:

def countElement(sample_list, element):
    return sample_list.count(element)


sample_list = ["a", "ab", "a", "abc", "ab", "ab"]
element = "ab"
print('{} has occurred {} times'.format(element, countElement(sample_list, element)))

Output Output

 ab has occurred 3 times

3) Using countof() method 3) 使用countof()方法

Operator module from python library consists of countof() method which helps to return the number of occurrence of the element from the lists. python 库中的操作员模块由countof()方法组成,该方法有助于从列表中返回元素的出现次数。 This method takes two arguments, ie, the list in which the count needs to be performed and the element which needs to be found.该方法取两个arguments,即需要进行计数的列表和需要查找的元素。 Moreover, you have to import the operator module before beginning the program using the import keyword as shown below:此外,您必须在开始程序之前使用import关键字导入 operator 模块,如下所示:

For example:例如:

sample_list = ["a", "ab", "a", "abc", "ab", "ab"]

import operator as op

print(op.countOf(sample_list,"a"))

Output Output

 2

4) Using counter() method 4) 使用counter()方法

Python possesses an in-built module named collections, including multiple methods to ease your programming. Python 拥有一个名为 collections 的内置模块,包括多种方法来简化您的编程。 One such method is a counter() method where elements are stored as a dictionary with keys and counts as values.一种这样的方法是counter()方法,其中元素存储为带有键的字典,计数作为值。

Therefore, the counter() method helps you return the total number of occurrences of a given element inside the given list by taking one parameter as the list in which the element is to be counted.因此, counter()方法通过将一个参数作为要计算元素的列表来帮助您返回给定列表中给定元素的出现总数。 Remember that you have to import the collections module to use the counter() method as shown in the below example:请记住,您必须导入 collections 模块才能使用counter()方法,如下例所示:

For example:例如:

sample_list = ["a", "ab", "a", "abc", "ab", "ab"]

from collections import Counter

print(Counter(sample_list))

c = Counter(sample_list) 
print(c["a"])

Output Output

 Counter({'ab': 3, 'a': 2, 'abc': 1}) 2

5) Using pandas library 5) 使用pandas

Pandas is the in-built python library, highly popular for data analysis and data manipulation. Pandas 是内置的 python 库,在数据分析和数据操作中非常流行。 It is an open-source tool with a large range of features and is widely used in the domains like machine learning and artificial intelligence.它是一个具有大量功能的开源工具,广泛应用于机器学习和人工智能等领域。

Pandas possess a wide range of default methods, one of which is the value_count() method. Pandas 拥有多种默认方法,其中之一是 value_count() 方法。 Along with the value_count() method, pandas use series, ie, a one-dimensional array with axis label.value_count()方法一起,pandas 使用系列,即轴为 label 的一维数组。

To count the occurrence of elements using pandas, you have to convert the given list into the series and then use the value_count() method, which returns the object in descending order.要使用 pandas 计算元素的出现次数,您必须将给定列表转换为系列,然后使用value_count()方法,该方法按降序返回 object。 By these, you can easily note that the first element is always the most frequently occurring element.通过这些,您可以很容易地注意到第一个元素始终是最常出现的元素。

Check out the below example for a better understanding of the Pandas library查看以下示例以更好地了解 Pandas 库

For example:例如:

import pandas as pd

sample_list = ["a", "ab", "a", "abc", "ab", "ab"]
count = pd.Series(sample_list).value_counts()
print(count["a"])

Output Output

 2

6) Using loops and dict in python 6) 在 python 中使用循环和字典

This is the most traditional method by which python count occurrences in the list that is by using the loop, conditional statement, and dictionaries.这是 python 使用循环、条件语句和字典计算列表中出现次数的最传统方法。 By this method, you have to create the empty dictionary and then iterate over the list.通过这种方法,您必须创建空字典,然后遍历列表。 Later, check if the element present in the list is available in the dictionary or not.稍后,检查列表中存在的元素是否在字典中可用。 If yes, then increase its value by one;如果是,则将其值加一; otherwise, introduce a new element in the dictionary and assign 1 to it.否则,在字典中引入一个新元素并为其赋值 1。 Repeat the same process until all the elements in the lists are visited.重复相同的过程,直到列表中的所有元素都被访问。

Remember that this method is quite different from the previous method using the loop and the counter variable.请记住,此方法与之前使用循环和计数器变量的方法有很大不同。 The early mentioned method does not make use of dictionary data structure, whereas this one does.前面提到的方法没有使用字典数据结构,而这个方法使用了。 At last, print the count of occurrence of each element as shown in the below example:最后,打印每个元素的出现次数,如下例所示:

For example:例如:

sample_list = ["a", "ab", "a", "abc", "ab", "ab"]

def countOccurrence(a):
  k = {}
  for j in a:
    if j in k:
      k[j] +=1
    else:
      k[j] =1
  return k

print(countOccurrence(sample_list))

Output Output

 {'a': 2, 'ab': 3, 'abc': 1}
a  =[random.randint(0,100) for i in range(100)]
list(zip(set(a),[a.count(i) for i in set(a)]))
test = [409.1, 479.0, 340.0, 282.4, 406.0, 300.0, 374.0, 253.3, 195.1, 269.0, 329.3, 250.7, 250.7, 345.3, 379.3, 275.0, 215.2, 300.0]

for i in test:
    print('{} numbers {}'.format(i, test.count(i)))
import pandas as pd
test = [409.1, 479.0, 340.0, 282.4, 406.0, 300.0, 374.0, 253.3, 195.1, 269.0, 329.3, 250.7, 250.7, 345.3, 379.3, 275.0, 215.2, 300.0]

#turning the list into a temporary dataframe
test  = pd.DataFrame(test)

#using the very convenient value_counts() function
df_counts = test.value_counts()
df_counts

then you can use df_counts.index and df_counts.values to get the data.那么您可以使用df_counts.indexdf_counts.values来获取数据。

x = ['Jess', 'Jack', 'Mary', 'Sophia', 'Karen',
     'Addison', 'Joseph','Jack', 'Jack', 'Eric', 'Ilona', 'Jason']
the_item = input('Enter the item that you wish to find : ')
how_many_times = 0 
for occurrence in x:
     if occurrence == the_item : 
          how_many_times += 1
print('The occurrence of', the_item, 'in', x,'is',how_many_times) 

Created a list of names wherein the name 'Jack' is repeated.创建了一个名称列表,其中重复了名称“Jack”。 In order to check its Occurrence, I ran a for loop in the list named x .为了检查它的出现,我在名为x的列表中运行了一个 for 循环。 Upon each iteration, if the loop variable attains the value same that of received from the user and stored in the variable the_item , the variable how_many_times gets incremented by 1. After attaining some value...We print how_many_times which stores the value of the occurance of the word 'jack'在每次迭代中,如果循环变量的值与从用户接收到的值相同并存储在变量 the_item 中,则变量the_item会增加 1。在达到某个值how_many_times how_many_times发生的值“杰克”这个词

def countfrequncyinarray(arr1):
    r=len(arr1)
    return {i:arr1.count(i) for i in range(1,r+1)}
arr1=[4,4,4,4]
a=countfrequncyinarray(arr1)
print(a)

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

相关问题 如何计算字典列表中某个项目的出现次数? - How can I count the occurrences of an item in a list of dictionaries? 给定一个项目,如何计算该项目在列表中的出现次数,如果不符合某些规定,则不打印该项目? - Given an item, how can I count the occurrences of said item in a list, and not print the item if it does not reach certain regulations? 如何计算列表列表中某个位置的特定元素的出现次数? - How do I count occurrences of a specific element in a position in a list of lists? 如何在不使用计数或计数器的情况下计算列表项的出现次数? - How to count the occurrences of a list item without using count or counter? 你如何计算 Python 列表中的出现次数? - How do you count occurrences in a list in Python? 如何计算另一个.txt文件中项目列表的出现次数? - How do I count the number of occurrences of a list of items in another .txt file? 如何替换二维列表数组中所有出现的项目 - How do I replace all occurrences of an item in a 2D list array 计算列表中每个项目的出现次数 - Count number of occurrences for each item in a list 计算(排序的)列表中给定项目的出现次数? - Count the number of occurrences of a given item in a (sorted) list? 计算没有list.count的列表中某项目的出现次数 - Count the number of occurrences of an item in a list without list.count
相关标签
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM