如何在 Python 列表中计算唯一值
Jinku Hu
2023年10月10日
Python
Python List
-
使用
collections.counter来计算 Python 列表中的唯一值 -
使用
set来计算 Python 列表中的唯一值 -
使用
numpy.unique计算 Python 列表中的唯一值
本文将介绍不同的方法来计算列表中的唯一值,使用以下方法。
collections.Counterset(listName)np.unique(listName)
使用 collections.counter 来计算 Python 列表中的唯一值
collections 是一个 Python 标准库,它包含 Counter 类来计算可哈希对象。
Counter 类有两个方法。
keys()返回列表中的唯一值。values()返回列表中每个唯一值的计数。
我们可以使用 len() 函数,通过传递 Counter 类作为参数来获得唯一值的数量。
示例代码
from collections import Counter
words = ["Z", "V", "A", "Z", "V"]
print(Counter(words).keys())
print(Counter(words).values())
print(Counter(words))
输出:
['V', 'A', 'Z']
[2, 1, 2]
3
使用 set 来计算 Python 列表中的唯一值
set 是一个无序的集合数据类型,它是可迭代、可变、没有重复元素的类型。当我们使用 set() 函数将列表转换为 set 后,我们可以得到 set 的长度来计算列表中的唯一值。
示例代码
words = ["Z", "V", "A", "Z", "V"]
print(len(set(words)))
输出:
3
使用 numpy.unique 计算 Python 列表中的唯一值
numpy.unique 返回输入数组类数据的唯一值,如果 return_counts 参数设置为 True,还返回每个唯一值的计数。
示例代码
import numpy as np
words = ["Z", "V", "A", "Z", "V"]
np.unique(words)
print(len(np.unique(words)))
输出:
3
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Jinku Hu
