在 Python 中查找元组列表中的频率

pythonserver side programmingprogramming更新于 2025/11/23 22:04:17

在 Python 中,许多不同类型的数据容器可能会混杂在一起。列表可以包含元素,每个元素都是一个元组。在本文中,我们将采用这样的列表,并查找元组中元素的频率,这些元素本身也是列表的元素。

使用 count 和 map

我们应用 lambda 函数来计数列表中存在的元组中的第一个元素。然后应用 map 函数来得出我们要搜索的元素的总数。

示例

# 初始化元组列表
listA = [('Apple', 'Mon'), ('Banana', 'Tue'), ('Apple', 'Wed')]

# 给定列表
print("给定元组列表:" ,listA)

# 元组列表中的频率
Freq_res = list(map(lambda i: i[0], listA)).count('Apple')

# 打印结果
print("The frequency of element is : ",Freq_res)

输出

运行上述代码得到以下结果:

Given list of tuples : [('Apple', 'Mon'), ('Banana', 'Tue'), ('Apple', 'Wed')]
The frequency of element is : 2

使用 Counter

我们还可以实现 Counter,它将计算元素出现的次数。我们使用 for 循环遍历列表中的每个元组。

示例

from collections import Counter

# 初始化元组列表
listA = [('Apple', 'Mon'), ('Banana', 'Tue'), ('Apple', 'Wed')]

# 给定列表
print("Given list of tuple : " ,listA)

# 元组列表中的频率
Freq_res = Counter(i[0] for i in listA)['Apple']

# 打印结果
print("The frequency of element is : ",Freq_res)

输出

运行上述代码得到以下结果 −

Given list of tuples : [('Apple', 'Mon'), ('Banana', 'Tue'), ('Apple', 'Wed')]
The frequency of element is : 2

相关文章


有用资源