如何确定元素在列表中出现的次数?

时间:2019-06-13 18:06:07

标签: python python-3.x python-2.7

我有如下所示的python列表

x = [False, 44, 3, 56, 3, [33, 45, 66, 3], ('c', 3), [4, 3]]*4

我想计算'3',在此列表中有多少次,我尝试过for循环,但它不在另一个列表和元组中计数,该怎么做?

预期输出为20。

7 个答案:

答案 0 :(得分:3)

您可以先使用this方法展平不规则列表,然后应用count(3)

from collections import Iterable, Counter

x = [False, 44, 3, 56, 3, [33, 45, 66, 3], ('c', 3), [4, 3]]*4

def flatten(l):
    for el in l:
        if isinstance(el, Iterable) and not isinstance(el, (str, bytes)):
            yield from flatten(el)
        else:
            yield el

freqs = list(flatten(x)).count(3)            

# 20

由于下面@bhlsing再次指出的原因,您可以遍历列表广告,计算出现次数3和总和

sum(1 for i in flatten(x) if i == 3)

或者,如果需要所有元素的频率,也可以使用Counter 。对于单个元素,如@bhlsing

所指出的,这将是一个过大的杀伤力
freqs = Counter(flatten(x))
print (freqs[3])

答案 1 :(得分:0)

缓慢,hacky的递归计数实现:

def recursive_count(lst, item):
    count = 0
        for elem in lst:
            if elem == item:
                count += 1
            elif type(elem) in (list, dict, set, tuple):  # or something else to check for iterale types
                count += recursive_count(elem, item)
    return count

答案 2 :(得分:0)

您可以使用12调用来检查对象是否可迭代

12.5

要使其类似于其他已发布的递归解决方案,请警惕hasattr(obj, '__iter__'),因为对于x = [False, 44, 3, 56, 3, [33, 45, 66, 3], ('c', 3), [4, 3]]*4 threes = 0 for item in x: # object is iterable, iterate over it if hasattr(item '__iter__'): for sub_item in item: if sub_item==3: threes +=1 # otherwise it isn't, go ahead and do an equality check elif item==3: threes +=1 threes 20 类型,这将导致无限递归。为避免这种情况:

hasattr(obj, '__iter__')

答案 3 :(得分:0)

功能

def count_element(obj, el):
    occurences = 0
    for item in obj:
        if isinstance(item, (list, tuple, set)):
            occurences += count_element(item, el)
        elif isinstance(item, type(el)):
            occurences += int(item == el)
    return occurences

用法:

x = [False, 44, 3, 56, 3, [33, 45, 66, 3], ('c', 3), [4, 3]] * 4
count = count_element(x, 3)

输出:

20

答案 4 :(得分:0)

许多方式之一:

def flatten(*args):
    for x in args:
        if isinstance(x, (list, tuple)):
            for y in flatten(*x):
                yield y
        else:
            yield x

x = [False, 44, 3, 56, 3, [33, 45, 66, 3], ('c', 3), [4, 3]]*4

print(len(list(filter(lambda x: x == 3, flatten(x)))))  

答案 5 :(得分:0)

在此解决方案中,您只需检查每个列表并在其中搜索3个

x = [False, 44, 3, 56, 3, [33, 45, 66, 3], ('c', 3), [4, 3]]*4
counter = 0
stash = []
stash.append(x)
while len(stash)!=0:
    print(stash)
    list = stash[0]
    for element in list:
        if hasattr(element, '__iter__') and not isinstance(element, str):
            stash.append(element)
        if element == 3:
            counter += 1
    stash.remove(list)
print(counter)

`

答案 6 :(得分:0)

您可能应该专门检查类型列表和元组。否则,您将无法正确计算多级列表中的字符串。

这是一个小型的递归函数,可以做到这一点:

x = [False, 44, 3, 56, 3, [33, 45, 66, 3], ('c', 3), [4, 3]]*4

def deepcount(value,target):
    if not isinstance(value,(list,tuple)):
        return int(value==target)
    return sum(deepcount(v,target) for v in value)

print(deepcount(x,3)) # 20

它将正确计算结构中的字符串:

y = ["abc", 12, "a",[23, False,"abc"]]*3

print(deepcount(y,"abc")) # 6
print(deepcount(y,"a"))   # 3