本文共 4273 字,大约阅读时间需要 14 分钟。
python 获取唯一值
In this article, we will be understanding 3 ways to get unique values from a Python list. While dealing with a huge amount of raw data, we often come across situations wherein we need to fetch out the unique and non-repeated set of data from the raw input data-set.
在本文中,我们将了解从Python列表中获取唯一值的3种方法 。 在处理大量原始数据时,我们经常会遇到需要从原始输入数据集中获取唯一且未重复的数据集的情况。
The methods listed below will help you solve this problem. Let’s get right into it!
下面列出的方法将帮助您解决此问题。 让我们开始吧!
Either of the following ways can be used to get unique values from a
以下两种方法均可用于从获取唯一值
As seen in our previous tutorial on , we know that Set stores a single copy of the duplicate values into it. This property of set can be used to get unique values from a list in Python.
如我们之前关于教程中所见,我们知道Set将重复值的单个副本存储到其中。 set的此属性可用于从Python列表中获取唯一值。
Syntax:
句法:
set(input_list_name)
Syntax:
句法:
list(set-name)
Example:
例:
list_inp = [100, 75, 100, 20, 75, 12, 75, 25] set_res = set(list_inp) print("The unique elements of the input list using set():\n") list_res = (list(set_res)) for item in list_res: print(item)
Output:
输出:
The unique elements of the input list using set():25751002012
In order to find the unique elements, we can apply a along with to achieve the same.
为了找到唯一的元素,我们可以将与一起使用以实现相同目的。
Syntax:
句法:
list.append(value)
Example:
例:
list_inp = [100, 75, 100, 20, 75, 12, 75, 25] res_list = []for item in list_inp: if item not in res_list: res_list.append(item) print("Unique elements of the list using append():\n") for item in res_list: print(item)
Output:
输出:
Unique elements of the list using append():10075201225
Python NumPy module has a built-in function named, numpy.unique to fetch unique data items from a numpy array.
Python NumPy模块具有一个名为numpy.unique的内置函数,用于从numpy数组中获取唯一的数据项。
Syntax:
句法:
numpy.array(list-name)
Syntax:
句法:
numpy.unique(numpy-array-name)
Example:
例:
import numpy as Nlist_inp = [100, 75, 100, 20, 75, 12, 75, 25] res = N.array(list_inp) unique_res = N.unique(res) print("Unique elements of the list using numpy.unique():\n")print(unique_res)
Output:
输出:
Unique elements of the list using numpy.unique():[12 20 25 75 100]
In this article, we have unveiled various ways to fetch the unique values from a set of data items in a Python list.
在本文中,我们揭示了从Python列表中的一组数据项中获取唯一值的各种方法。
翻译自:
python 获取唯一值
转载地址:http://voqzd.baihongyu.com/