python 获取唯一值
Say you have a list that contains duplicate numbers:
假设您有一个包含重复数字的列表:
numbers = [1, 1, 2, 3, 3, 4]
But you want a list of unique numbers.
但是,您需要一个唯一编号列表。
unique_numbers = [1, 2, 3, 4]
There are a few ways to get a list of unique values in Python. This article will show you how.
有几种方法可以获取Python中唯一值的列表。 本文将向您展示如何。
选项1 –使用集合获取唯一元素 (Option 1 – Using a Set to Get Unique Elements)
Using a set
one way to go about it. A set is useful because it contains unique elements.
使用一set
方法进行操作。 集合很有用,因为它包含唯一元素。
You can use a set to get the unique elements. Then, turn the set into a list.
您可以使用一组来获取唯一元素。 然后,将集合变成一个列表。
Let’s look at two approaches that use a set and a list. The first approach is verbose, but it’s useful to see what’s happening each step of the way.
让我们看一下使用集合和列表的两种方法。 第一种方法很冗长,但是查看此过程中每个步骤正在发生的事情很有用。
numbers = [1, 2, 2, 3, 3, 4, 5]
def get_unique_numbers(numbers):
list_of_unique_numbers = []
unique_numbers = set(numbers)
for number in unique_numbers:
list_of_unique_numbers.append(number)
return list_of_unique_numbers
print(get_unique_numbers(numbers))
# result: [1, 2, 3, 4, 5]
Let’s take a closer look at what’s happening. I’m given a list of numbers, numbers
. I pass this list into the function, get_unique_numbers
.
让我们仔细看看发生了什么。 我得到了一个数字