python 获取唯一值_Python唯一列表–如何获取列表或数组中的所有唯一值

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.

让我们仔细看看发生了什么。 我得到了一个数字

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值