ChatGPT解决这个技术问题 Extra ChatGPT

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

给定一个项目,我如何计算它在 Python 列表中的出现次数?


M
Mateen Ulhaq

如果您只需要单个项目的计数,请使用 count 方法:

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

重要提示:如果您要计算多个不同的项目,这会非常慢

每个 count 调用都会遍历整个 n 元素列表。在循环 n 次中调用 count 意味着总共 n * n 次检查,这可能对性能造成灾难性影响。

如果您想计算多个项目,请使用 Counter,它只进行 n 个总检查。


mylist = [1,7,7,7,3,9,9,9,7,9,10,0] print sorted(set([i for i in mylist if mylist.count(i)>2]))
在我的例子中计算唯一元素会产生以下时间:list.count() 114.19 秒,numpy.unique(list, return_counts = True) 0.53 秒和 0.17 秒 { 3}。差异是惊人的。
T
Trenton McKinney

如果您使用的是 Python 2.7 或 3.x 并且想要每个元素的出现次数,请使用 Counter

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

我发现,当大量使用它(谈论数百万个字符串)时,由于它调用 isinstance,它非常慢。因此,如果您确定要使用的数据,最好编写一个没有类型和实例检查的自定义函数。
@BramVanroy:isinstance 叫什么?即使有数百万个字符串,调用 Counter 也只涉及一次 isinstance 调用,以检查其参数是否为映射。你很可能一直误判你吃的东西。
您误解了我的意思:计数器在创建计数器之前检查您的数据类型。如果您提前知道数据的类型,这需要相对较长的时间。如果你看一下 Counter 的更新方法,你会发现它在做某事之前必须经过三个 if 语句。如果您经常调用更新,这会很快增加。当你可以控制你的数据并且你知道输入确实是一个可迭代的,那么你可以跳过前两个检查。正如我所说,我只在处理数百万次更新时才注意到这一点,所以这是一个边缘案例。
@BramVanroy:如果您要执行数百万次 更新 而不仅仅是计算数百万个字符串,那就另当别论了。 Counter 中的优化工作已用于计算大型可迭代对象,而不是计算许多可迭代对象。与手动实现相比,使用 Counter 计算一百万个字符串的迭代会更快。如果您想用许多可迭代对象调用 update,您可以通过将它们与 itertools.chain 加入一个可迭代对象来加快处理速度。
如果您想对结果进行排序 how-to-sort-counter-by-value-python --> x = Counter({'a':5, 'b':3, 'c':7}) x.most_common()
M
Martijn Pieters

计算列表中一项的出现次数

要计算一个列表项的出现次数,您可以使用 count()

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

计算列表中所有项目的出现次数也称为“计数”列表或创建计数计数器。

使用 count() 计算所有项目

要计算 l 中项目的出现次数,可以简单地使用列表推导和 count() 方法

[[x,l.count(x)] for x in set(l)]

(或类似地使用字典 dict((x,l.count(x)) for x in set(l))

例子:

>>> l = ["a","b","b"]
>>> [[x,l.count(x)] for x in set(l)]
[['a', 1], ['b', 2]]
>>> dict((x,l.count(x)) for x in set(l))
{'a': 1, 'b': 2}

使用 Counter() 计算所有项目

或者,还有来自 collections 库的更快的 Counter

Counter(l)

例子:

>>> l = ["a","b","b"]
>>> from collections import Counter
>>> Counter(l)
Counter({'b': 2, 'a': 1})

计数器快多少?

我检查了统计列表的 Counter 有多快。我用几个 n 值尝试了这两种方法,似乎 Counter 快了大约 2 的常数因子。

这是我使用的脚本:

from __future__ import print_function
import timeit

t1=timeit.Timer('Counter(l)', \
                'import random;import string;from collections import Counter;n=1000;l=[random.choice(string.ascii_letters) for x in range(n)]'
                )

t2=timeit.Timer('[[x,l.count(x)] for x in set(l)]',
                'import random;import string;n=1000;l=[random.choice(string.ascii_letters) for x in range(n)]'
                )

print("Counter(): ", t1.repeat(repeat=3,number=10000))
print("count():   ", t2.repeat(repeat=3,number=10000)

和输出:

Counter():  [0.46062711701961234, 0.4022796869976446, 0.3974247490405105]
count():    [7.779430688009597, 7.962715800967999, 8.420845870045014]

Counter 对于更大的列表方式更快。列表理解方法是 O(n^2),Counter 应该是 O(n)。
Counter 的速度不是 2 倍,Counter 的速度是 n 倍(O(n^2) vs O(n))。
我发现,当大量使用它(谈论数百万个字符串)时,由于它调用 isinstance,它非常慢。因此,如果您确定要使用的数据,最好编写一个没有类型和实例检查的自定义函数。
t
the

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

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

这看起来像是我在激烈的战斗中经常提出的一种结构,但它会运行 len(a) 次,这意味着二次运行时复杂度(因为每次运行再次取决于 len(a))。
dict((i,a.count(i)) for i in set(a)) 会更正确、更快吗?
@hugo24:有点,但在最坏的情况下它不会越来越快;这将需要 n * (number of different items) 个操作,不包括构建集合所需的时间。使用 collections.Counter 确实要好得多。
派对很晚,但如果列表包含多个 i 实例,则不会跟随代码抛出错误,因为它会尝试在字典中输入多个具有相同值的键。 dict((i, a.count(i)) for i in a)
@rp1 你可以自己试试看,后面的键值对只是覆盖了同一个键的前一个条目,例如 dict([(1, 2), (1, 3)]) 返回 {1: 3}
C
Community

给定一个项目,我如何计算它在 Python 列表中的出现次数?

这是一个示例列表:

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

列表计数

list.count 方法

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

这适用于任何列表。元组也有这种方法:

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

集合.计数器

然后是 collections.Counter。您可以将任何可迭代对象转储到 Counter 中,而不仅仅是列表,并且 Counter 将保留元素计数的数据结构。

用法:

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

计数器基于 Python 字典,它们的键是元素,因此键需要是可散列的。它们基本上就像允许冗余元素进入它们的集合。

collections.Counter 的进一步使用

您可以使用计数器中的可迭代对象添加或减去:

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

您还可以使用计数器进行多组操作:

>>> 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})

为什么不是熊猫?

另一个答案表明:

为什么不使用熊猫?

Pandas 是一个通用库,但它不在标准库中。将其添加为要求并非易事。

列表对象本身以及标准库中都有针对此用例的内置解决方案。

如果您的项目还不需要 pandas,那么仅仅为此功能要求它是愚蠢的。


虽然“为什么不使用 Pandas”是合适的,但它可能应该伴随着“何时使用 NumPy”,即对于大型数字数组。决定因素不仅仅是项目限制,还有 NumPy 的内存效率,这在大数据中变得显而易见。
感谢您提到 Pandas/etc 是一个严重的依赖项。其中一些软件包具有负面影响。因此,为琐碎的需求添加这些资产可能会花费大量时间和美元。就我个人而言,我体验过 Numpy 和 SciPi 将 30 分钟添加到我们的 CI 管道中,并且需要数天才能正确获取包缓存。很棒的套餐,但有时会有隐藏的费用。 +1 了
E
Eugene Yarmash

list.count(x) 返回 x 在列表中出现的次数

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


N
Nico Schlömer

我已经将所有建议的解决方案(以及一些新的解决方案)与 perfplot(我的一个小项目)进行了比较。

计数一项

对于足够大的数组,事实证明

numpy.sum(numpy.array(a) == 1)

比其他解决方案略快。

https://i.stack.imgur.com/vTw7i.png

计算所有项目

As established before

numpy.bincount(a)

是你想要的。

https://i.stack.imgur.com/IE6L3.png

重现绘图的代码:

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,
    )

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()

numpy.bincount() 仅适用于具有 int 项目的列表。
第一个程序实际上并没有测量计数一个项目,是吗?看起来它和第二个程序一样。你能检查/修复它吗?我认为numpy.random.randint(0, 100, n).tolist()会更好。使用您的 list(numpy.random.randint(0, 100, n)),您在 Python 列表中有 NumPy 整数,这看起来很奇怪/不切实际。
f
flonk

如果您想一次计算所有值,您可以使用 numpy 数组和 bincount 快速完成,如下所示

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

这使

>>> array([0, 3, 1, 1, 2])

T
Thirupathi Thangavel

如果您可以使用 pandas,那么 value_counts 就可以进行救援。

>>> 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

它也会根据频率自动对结果进行排序。

如果您希望结果在列表列表中,请执行以下操作

>>> pd.Series(a).value_counts().reset_index().values.tolist()
[[1, 3], [4, 2], [3, 1], [2, 1]]

但是,pandas 有很多开销,因此它是处理少量数据时最慢的解决方案。 stackoverflow.com/a/46195192/125507
C
Community

为什么不使用熊猫?

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

输出:

a    3
d    2
b    1
c    1
dtype: int64

如果您正在寻找特定元素的计数,例如 a,请尝试:

my_count['a']

输出:

3

D
D Blanc

我今天遇到了这个问题,并在我想检查 SO 之前推出了自己的解决方案。这个:

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

对于大型列表来说真的非常慢。我的解决方案

def occurDict(items):
    d = {}
    for i in items:
        if i in d:
            d[i] = d[i]+1
        else:
            d[i] = 1
return d

实际上比 Counter 解决方案要快一点,至少对于 Python 2.7 来说是这样。


计数器对条目进行排序,而您的不是,因此速度差异(在撰写本文时为真,不确定是否是在您写答案时。不过,它可能与向下滚动的人有关。)
Python 2 中的 Counter 有点慢,是的。然而,它使用 C 优化代码在 Python 3 中进行计数,现在可以轻松击败您的循环。
T
Tim Skov Jacobsen

使用 itertools.groupby() 计算所有元素

获取列表中所有元素的计数的另一种可能性是通过 itertools.groupby()

带有“重复”计数

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)

退货

[('a', 3), ('t', 1), ('q', 1), ('a', 1), ('d', 1), ('a', 1), ('d', 1), ('c', 1)]

请注意它如何将前三个 a 组合为第一组,而其他 a 组则出现在列表的更下方。这是因为输入列表 L 未排序。如果这些组实际上应该是分开的,这有时可能是一个好处。

具有独特的计数

如果需要唯一组计数,只需对输入列表进行排序:

counts = [(i, len(list(c))) for i,c in groupby(sorted(L))]
print(counts)

退货

[('a', 5), ('c', 1), ('d', 2), ('q', 1), ('t', 1)]

注意:为了创建唯一计数,与 groupby 解决方案相比,许多其他答案提供了更简单、更易读的代码。但这里显示的是与重复计数示例平行。


W
Wes Turner
# 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)]

@plaes:怎么会?如果通过“企业”,您的意思是“记录”以准备 Py3k 注释,我同意。
这是一个很好的例子,因为我主要在 2.7 中开发,但必须有到 2.4 的迁移路径。
H
Harsh Gundecha

虽然这是一个很老的问题,但由于我没有找到一个班轮,所以我做了一个。

# 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}

不要将列表推导用于副作用。请参阅:Is it Pythonic to use list comprehensions for just side effects?
A
Akash Swain

以下是三种解决方案:

最快的是使用 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))

结果

#解决方案 1 - 更快

{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

#解决方案 2 - 快速

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

#解决方案 3 - 慢

{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

而是使用 @user52028778 在上述解决方案中提到的 Counter
@KishanK如果您看到我的答案,我也尝试过使用 Counter(Solution 2),但是使用循环的 Solution1 仍然比它运行得更快。
@AkashSwain 在您实施的方法中,我想您可以通过从列表中删除已计数的元素来使其运行得更快一些,因为 for 循环不必检查这些...我将复制列表,然后从复制的列表中删除列出并执行 for 循环,我想您也必须以相反的顺序执行循环,因为您将从列表中删除内容...
A
Andreas K.

建议使用 numpy 的 bincount,但它仅适用于具有 非负整数的一维数组。此外,结果数组可能会令人困惑(它包含原始列表中从 min 到 max 的整数的出现,并将缺失的整数设置为 0)。

使用 numpy 执行此操作的更好方法是使用 unique 函数并将属性 return_counts 设置为 True。它返回一个元组,其中包含唯一值数组和每个唯一值出现的数组。

# a = [1, 1, 0, 2, 1, 0, 3, 3]
a_uniq, counts = np.unique(a, return_counts=True)  # array([0, 1, 2, 3]), array([2, 3, 1, 2]

然后我们可以将它们配对为

dict(zip(a_uniq, counts))  # {0: 2, 1: 3, 2: 1, 3: 2}

它也适用于其他数据类型和“二维列表”,例如

>>> a = [['a', 'b', 'b', 'b'], ['a', 'c', 'c', 'a']]
>>> dict(zip(*np.unique(a, return_counts=True)))
{'a': 3, 'b': 3, 'c': 2}

e
eyquem

计算具有共同类型的不同元素的数量:

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')

3 ,而不是 6


您也可以将其写为 sum(bool(el[0]=='A' and el[1] in '01234') for el in li)
v
vishes_shell

您还可以使用内置模块 operatorcountOf 方法。

>>> import operator
>>> operator.countOf([1, 2, 3, 4, 1, 4, 1], 1)
3

countOf 是如何实现的?它与更明显的 list.count(受益于 C 实现)相比如何?有什么优势吗?
I
IPython

我会使用 filter(),以 Lukasz 为例:

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

这会在 python 3.5 中引发异常“对象过滤器没有 len()”
在 Python 3 中,您必须使用 list() 将过滤器对象转换为列表。
F
Fatemeh Asgarinejad

给定一个列表 X

 import numpy as np
 X = [1, -1, 1, -1, 1]

显示此列表元素的 i: frequency(i) 的字典是:

{i:X.count(i) for i in np.unique(X)}

输出:

{-1: 2, 1: 3}

numpy 是否在创建列表时以智能方式预先计算?如果不是,这是一个 O(n^2)。
G
Golden Lion

使用 %timeit 查看哪个操作更有效。 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)

b
blue-sky

可能不是最有效的,需要额外通过才能删除重复项。

功能实现:

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

返回:

{('c', 1), ('b', 3), ('a', 2)}

或返回 dict

print(dict(map(lambda x  : (x , list(arr).count(x)) , arr)))

返回:

{'b': 3, 'c': 1, 'a': 2}

A
Abel Rodríguez

或者,您也可以自己实现计数器。这就是我的做法:

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)

输出:{'me': 2, 'you': 3, 'they': 1}


b
ben othman zied
mot = ["compte", "france", "zied"]
lst = ["compte", "france", "france", "france", "france"]
dict((x, lst.count(x)) for x in set(mot))

这给了

{'compte': 1, 'france': 4, 'zied': 0}

这对我有用,尽管由于 set 函数,额外的重复数据删除 'mot' 变量是多余的,所以这也有效: lst = ["compte", "france", "france", "france", "france" ] dict((x, lst.count(x)) for x in set(lst))
w
whackamadoodle3000
sum([1 for elem in <yourlist> if elem==<your_value>])

这将返回 your_value 的出现次数


M
Mohamed Fathallah
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))

这将递归计数或搜索列表中的项目,即使它在列表列表中


我不知道为什么有人只是对答案投了反对票,而且它完全有用
d
dimension

如果您想要特定元素的多次出现:

>>> 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])

T
Tomerikoo
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)))

M
Mehdi Fekih
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

那么您可以使用 df_counts.indexdf_counts.values 来获取数据。


L
LunaticXXD10
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) 

创建了一个名称列表,其中重复了名称“Jack”。为了检查它的出现,我在名为 x 的列表中运行了一个 for 循环。在每次迭代中,如果循环变量的值与从用户接收并存储在变量 the_item 中的值相同,则变量 how_many_times 增加 1。在达到某个值之后......我们打印 how_many_times存储单词“jack”出现的值