如何在python中构造一组列表项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15768757/
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 construct a set out of list items in python?
提问by securecoding
I have a listof filenames in python and I would want to construct a setout of all the filenames.
我list在 python 中有一个文件名,我想set从所有文件名中构造一个。
filelist=[]
for filename in filelist:
set(filename)
This does not seem to work. How can do this?
这似乎不起作用。怎么能做到这一点?
采纳答案by mgilson
If you have a list of hashable objects (filenames would probably be strings, so they should count):
如果你有一个可散列对象的列表(文件名可能是字符串,所以它们应该算数):
lst = ['foo.py', 'bar.py', 'baz.py', 'qux.py', Ellipsis]
you can construct the set directly:
你可以直接构造集合:
s = set(lst)
In fact, setwill work this way with any iterable object!(Isn't duck typing great?)
事实上,任何可迭代对象set都会以这种方式工作!(鸭子打字不是很好吗?)
If you want to do it iteratively:
如果你想迭代地做:
s = set()
for item in iterable:
s.add(item)
But there's rarely a need to do it this way. I only mention it because the set.addmethod is quite useful.
但很少需要这样做。我之所以提到它,是因为该set.add方法非常有用。
回答by Raymond Hettinger
The most direct solution is this:
最直接的解决办法是这样的:
s = set(filelist)
The issue in your original code is that the values weren't being assigned to the set. Here's the fixed-up version of your code:
原始代码中的问题是值没有分配给set。这是您的代码的固定版本:
s = set()
for filename in filelist:
s.add(filename)
print(s)
回答by Adi Ml
Here is another solution:
这是另一个解决方案:
>>>list1=["C:\","D:\","E:\","C:\"]
>>>set1=set(list1)
>>>set1
set(['E:\', 'D:\', 'C:\'])
In this code I have used the set method in order to turn it into a set and then it removed all duplicate values from the list
在这段代码中,我使用了 set 方法将它变成了一个集合,然后它从列表中删除了所有重复的值
回答by HelloGoodbye
You can do
你可以做
my_set = set(my_list)
or, for Python 3,
或者,对于 Python 3,
my_set = {*my_list}
to create a set from a list. Conversely, you can also do
从列表创建一个集合。相反,你也可以这样做
my_list = list(my_set)
or, for Python 3,
或者,对于 Python 3,
my_list = [*my_set]
to create a list from a set.
从集合创建列表。
Just note that the order of the elements in a list is generally lost when converting the list to a set since a set is inherently unordered. (One exception in CPython, though, seems to be if the list consists only of non-negative integers, but I assume this is a consequence of the implementation of sets in CPython and that this behavior can vary between different Python implementations.)
请注意,在将列表转换为集合时,列表中元素的顺序通常会丢失,因为集合本质上是无序的。(不过,CPython 中的一个例外似乎是列表仅包含非负整数,但我认为这是 CPython 中集合实现的结果,并且这种行为可能因不同的 Python 实现而异。)
回答by muknerd
Simply put the line:
简单地说一下:
new_list = set(your_list)
回答by lbsweek
One general way to construct set in iterative way like this:
一种以迭代方式构造集合的通用方法,如下所示:
aset = {e for e in alist}

