用 Python 从列表中获取唯一值

在本文中,我们将了解 3种从Python列表中获取唯一值的方法 。在处理大量原始数据时,我们经常会遇到需要从原始输入数据集中提取唯一且不重复的数据集的情况。

下面列出的方法将帮助您解决此问题。让我们开门见山吧!


如何在Python中从列表中获取唯一值

可以通过以下两种方式从List in Python:获取唯一值

  • Python set()方法
  • 结合使用Python list.append()方法和for循环
  • 使用PYTHON Numpy.Unique()方法

1.从列表中获取唯一值的Pythonset()

正如我们在上一篇关于PythonSet的教程中所看到的,我们知道Set将重复值的单个副本存储到其中。Set的此属性可用于从Python中的列表中获取唯一值。

  • 首先,我们需要使用set()函数将输入列表转换为set。

语法:

1set(input_list_name)
  • 当列表转换为SET时,只会将所有重复元素的单个副本放入其中。
  • 然后,我们必须使用以下命令/语句将集合转换回列表:

语法:

1list(set-name)
  • 最后,打印新列表

示例:

1list_inp = [100, 75, 100, 20, 75, 12, 75, 25] 
2
3set_res = set(list_inp) 
4print("The unique elements of the input list using set():\n") 
5list_res = (list(set_res))
6
7for item in list_res: 
8    print(item)

输出:

1The unique elements of the input list using set():
2
325
475
5100
620
712

2. Python list.append()和for循环

为了找到唯一的元素,我们可以对loop](/community/tutorials/python-for-loop-example)应用PythonforList.append()function来实现相同的目的。

  • 首先,我们创建一个新的(空)列表,即res_list。
  • 之后,使用for循环检查创建的新列表(Res_List)中是否存在特定元素。如果元素不存在,则使用append()方法将其添加到新列表中。

语法:

1list.append(value)
  • 万一我们在遍历新列表中已经存在的元素时遇到一个元素,即重复元素,在这种情况下它会被for loop.我们将使用if statement来检查它是唯一的元素还是重复的元素。

示例:

 1list_inp = [100, 75, 100, 20, 75, 12, 75, 25] 
 2
 3res_list = []
 4
 5for item in list_inp: 
 6    if item not in res_list: 
 7        res_list.append(item) 
 8
 9print("Unique elements of the list using append():\n")    
10for item in res_list: 
11    print(item)

输出:

1Unique elements of the list using append():
2
3100
475
520
612
725

3.创建包含唯一项的列表的Python numpy.only()函数

Python NumPy模块有一个名为numpy.Unique的内置函数,用于从NumPy数组中获取唯一的数据项。

  • 为了从Python列表中获取唯一元素,我们需要使用以下命令将列表转换为NumPy数组:

语法:

1numpy.array(list-name)
  • 接下来,我们将使用numpy.only()方法从NumPy数组获取唯一的数据项
  • 最后,我们将打印结果列表。

语法:

1numpy.unique(numpy-array-name)

示例:

1import numpy as N
2list_inp = [100, 75, 100, 20, 75, 12, 75, 25] 
3
4res = N.array(list_inp) 
5unique_res = N.unique(res) 
6print("Unique elements of the list using numpy.unique():\n")
7print(unique_res)

输出:

1Unique elements of the list using numpy.unique():
2
3[12 20 25 75 100]

结论

在本文中,我们介绍了从Python列表中的一组数据项获取唯一值的各种方法。


参考文献

Published At
Categories with 技术
Tagged with
comments powered by Disqus