简体   繁体   中英

How to construct a set out of list items in python?

I have a list<\/code> of filenames in python and I would want to construct a set<\/code> out of all the filenames.

filelist=[]
for filename in filelist:
    set(filename)

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, set will work this way with any iterable object! (Isn't duck typing great?)


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.add method is quite useful.

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:

s = set()
for filename in filelist:
    s.add(filename)
print(s)

You can do

my_set = set(my_list)

or, in Python 3,

my_set = {*my_list}

to create a set from a list. Conversely, you can also do

my_list = list(my_set)

or, in 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.)

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

简单地说一下:

new_list = set(your_list)

一种以迭代方式构造集合的通用方法,如下所示:

aset = {e for e in alist}

您还可以使用列表理解来创建集合。

s = {i for i in range(5)}

以上所有答案都是正确的,但是如果您想保留列表的顺序,则需要按照以下步骤进行

list(dict.fromkeys(your_list))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM