如何使列表只包含 Python 中的不同元素? [英] How to make lists contain only distinct element in Python?

查看:41
本文介绍了如何使列表只包含 Python 中的不同元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Python 中有一个列表,如何使其值唯一?

I have a list in Python, how can I make it's values unique?

推荐答案

最简单的就是先转换成集合再转换回列表:

The simplest is to convert to a set then back to a list:

my_list = list(set(my_list))

这样做的一个缺点是它不会保留顺序.您可能还需要考虑首先使用集合是否是更好的数据结构,而不是列表.

One disadvantage with this is that it won't preserve the order. You may also want to consider if a set would be a better data structure to use in the first place, instead of a list.

这篇关于如何使列表只包含 Python 中的不同元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆