You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计一个列表中的元素在另一个列表中的出现次数

解决方案

你的问题在于遍历l2的每个元素会导致重复输出相同元素的统计结果,同时你需要根据元素是否在l1中来决定显示它在l2中的出现次数还是0。以下是两种实现方式:

方法1:基础实现(适用于小列表)

先获取l2中的唯一元素并保留原有顺序,再逐个判断元素是否在l1中,统计对应次数:

l1 = ['hello', 'hi']
l2 = ['hey', 'hi', 'hello', 'hello']

# 通过dict.fromkeys获取l2的唯一元素并保持顺序
for item in dict.fromkeys(l2):
    count = l2.count(item) if item in l1 else 0
    print(f'{count}: {item}')

输出结果:

0: hey
1: hi
2: hello

方法2:高效实现(适用于大列表)

使用collections.Counter预先统计l2中所有元素的出现次数,避免重复调用count()带来的性能损耗:

from collections import Counter

l1 = ['hello', 'hi']
l2 = ['hey', 'hi', 'hello', 'hello']

# 一次性统计l2中所有元素的出现次数
l2_counts = Counter(l2)

for item in dict.fromkeys(l2):
    count = l2_counts[item] if item in l1 else 0
    print(f'{count}: {item}')

输出结果与方法1一致。

补充:仅统计l1元素在l2中的次数

如果不需要包含l2中不在l1的元素,可以直接遍历l1:

l1 = ['hello', 'hi']
l2 = ['hey', 'hi', 'hello', 'hello']

for item in l1:
    print(f'{l2.count(item)}: {item}')

输出结果:

2: hello
1: hi

内容的提问来源于stack exchange,提问作者user19533292

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 16:30:50