Python 如何确保列表包含唯一元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4743409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to ensure list contains unique elements?
提问by Cuga
I have a class containing a list of strings. Say:
我有一个包含字符串列表的类。说:
ClassName:
- list_of_strings
I need to enforce that this list of strings contains unique elements. Unfortunately, I can't change this list_of_strings to another type, like a set.
我需要强制此字符串列表包含唯一元素。不幸的是,我无法将此 list_of_strings 更改为另一种类型,例如集合。
In the addToList(str_to_add)function, I want to guarantee string uniqueness. How can I best do this? Would it be practical to add the string being added to the list, convert to a set, then back to a list, and then reassign that to the object?
在addToList(str_to_add)函数中,我想保证字符串的唯一性。我怎样才能最好地做到这一点?将要添加的字符串添加到列表中,转换为集合,然后返回到列表,然后将其重新分配给对象是否可行?
Here's the method I need to update:
这是我需要更新的方法:
def addToList(self, str_to_add):
self.list_of_strings.append(str_to_add)
Thanks!
谢谢!
采纳答案by ephemient
def addToList(self, str_to_add):
if str_to_add not in self.list_of_strings:
self.list_of_strings.append(str_to_add)
回答by icktoofay
You indeed could do the list-to-set-to-list operation you described, but you could also use the inoperator to check if the element is already in the list before appending it.
您确实可以执行您描述的 list-to-set-to-list 操作,但您也可以使用in运算符在附加之前检查元素是否已经在列表中。
回答by Ignacio Vazquez-Abrams
Either check for the presence of the string in the list with in, or use a setin parallel that you can check and add to.
要么使用 来检查列表中是否存在字符串in,要么set并行使用可以检查并添加到的 。
回答by void-pointer
One possible way to do this would be to create a hash set and iterate through the list, adding the elements to the set; a second iteration could be used to remove any duplicates.
一种可能的方法是创建一个散列集并遍历列表,将元素添加到集合中;第二次迭代可用于删除任何重复项。
回答by Walker
Perhaps we can do like this:
也许我们可以这样做:
def addToList(self, str_to_add):
def addToList(self, str_to_add):
try:
self.list_of_strings.index(str_to_add)
except:
self.list_of_strings.append(str_to_add)
Well, I don't know whether it's the same mechanism with if/else yet.
好吧,我不知道它是否与 if/else 机制相同。

