Python 中获取列表的唯一值
Python 中的列表是一系列放置在 [] 中的项目,这些项目的数据类型可能相同也可能不同。它还可以包含重复项。在本文中,我们将了解如何从列表中提取唯一的项目。
使用 append()
在这种方法中,我们将首先创建一个新的空列表,然后仅当元素不在此新列表中时才将元素追加到此新列表中。for 循环与 not in 条件一起使用。它检查传入元素是否存在,并且仅当它不存在时才追加它。
示例
def catch_unique(list_in):
# intilize an empty list
unq_list = []
# Check for elements
for x in list_in:
# check if exists in unq_list
if x not in unq_list:
unq_list.append(x)
# print list
for x in unq_list:
print(x)
Alist = ['Mon', 'Tue', 'Mon', 'wed', 40, 40]
print("Unique values from the list is")
catch_unique(Alist)输出
运行以上代码将得到以下结果:
Unique values from the list is Mon Tue wed 40
使用集合
集合只包含唯一的值。在这种方法中,我们将列表转换为集合,然后将集合转换回列表,该列表包含所有唯一元素。
示例
Alist = ['Mon', 'Tue', 'Mon', 'wed', 40, 40]
A_set = set(Alist)
New_List=list(A_set)
print("Unique values from the list is")
print(New_List)输出
运行以上代码将得到以下结果:
Unique values from the list is [40, 'Tue', 'wed', 'Mon']
使用 numpy
numpy 库有一个名为 unique 的函数,它可以直接将列表作为输入,并将唯一元素作为新列表输出。
示例
import numpy as np
Alist = ['Mon', 'Tue', 'Mon', 'wed', 40, 40]
print("The unique values from list is: ")
print(np.unique(Alist))输出
运行以上代码将得到以下结果:
The unique values from list is: ['40' 'Mon' 'Tue' 'wed']
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP