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

前端 未结 6 1944
无人共我
无人共我 2020-11-27 12:25

I have a list of filenames in python and I would want to construct a set out of all the filenames.

filelist=[]
for filename in file         


        
6条回答
  •  情书的邮戳
    2020-11-27 12:55

    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.)

提交回复
热议问题