从Python列表中获取唯一值
时间:2020-02-23 14:42:17 来源:igfitidea点击:
在本文中,我们将了解从Python列表中获取唯一值的3种方法。
在处理大量原始数据时,我们经常遇到需要从原始输入数据集中获取唯一且未重复的数据集的情况。
从Python列表中获取唯一值的方法
可以使用以下两种方法之一从Python列表中获取唯一值:
- Python set()方法
- 使用Python list.append()方法和for循环
- 使用Python numpy.unique()方法
1. Python Set()从列表中获取唯一值
从上一本关于Python Set的教程中可以看出,我们知道Set将重复值的单个副本存储到其中。
set的此属性可用于从Python列表中获取唯一值。
- 最初,我们需要使用set()函数将输入列表转换为set。
语法:
set(input_list_name)
当列表转换为set时,所有重复元素的仅一个副本将放入其中。
然后,我们将必须使用以下命令/语句将集合转换回列表:
语法:
list(set-name)
- 最后,列印新列表
例:
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)
输出:
The unique elements of the input list using set(): 25 75 100 20 12
2. Python list.append()和for循环
为了找到唯一的元素,我们可以将Python for循环与list.append()函数一起使用以实现相同的目的。
首先,我们创建一个新的(空)列表,即res_list。
此后,使用for循环,我们检查所创建的新列表(res_list)中是否存在特定元素。
如果不存在该元素,则使用append()方法将其添加到新列表中。
语法:
list.append(value)
- 万一我们遍历新列表中已经存在的元素,即重复元素,在这种情况下,它被for循环所忽略。
我们将使用if语句检查它是唯一元素还是重复元素。
例:
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)
输出:
Unique elements of the list using append(): 100 75 20 12 25
3. Python numpy.unique()函数创建包含唯一项的列表
Python NumPy模块具有一个内置函数numpy.unique,用于从numpy数组中获取唯一的数据项。
- 为了从Python列表中获取唯一元素,我们需要使用以下命令将列表转换为NumPy数组:
语法:
numpy.array(list-name)
- 接下来,我们将使用numpy.unique()方法从numpy数组中获取唯一数据项
- 最后,我们将打印结果列表。
语法:
numpy.unique(numpy-array-name)
例:
import numpy as N list_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)
输出:
Unique elements of the list using numpy.unique(): [12 20 25 75 100]