Python set to list

后端 未结 7 1861
谎友^
谎友^ 2020-12-22 18:28

How can I convert a set to a list in Python? Using

a = set([\"Blah\", \"Hello\"])
a = list(a)

doesn\'t work. It gives me:

         


        
相关标签:
7条回答
  • 2020-12-22 19:05

    before you write set(XXXXX) you have used "set" as a variable e.g.

    set = 90 #you have used "set" as an object
    …
    …
    a = set(["Blah", "Hello"])
    a = list(a)
    
    0 讨论(0)
  • 2020-12-22 19:07
    s = set([1,2,3])
    print [ x for x in iter(s) ]
    
    0 讨论(0)
  • 2020-12-22 19:10

    You've shadowed the builtin set by accidentally using it as a variable name, here is a simple way to replicate your error

    >>> set=set()
    >>> set=set()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'set' object is not callable
    

    The first line rebinds set to an instance of set. The second line is trying to call the instance which of course fails.

    Here is a less confusing version using different names for each variable. Using a fresh interpreter

    >>> a=set()
    >>> b=a()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'set' object is not callable
    

    Hopefully it is obvious that calling a is an error

    0 讨论(0)
  • 2020-12-22 19:13

    Your code does work (tested with cpython 2.4, 2.5, 2.6, 2.7, 3.1 and 3.2):

    >>> a = set(["Blah", "Hello"])
    >>> a = list(a) # You probably wrote a = list(a()) here or list = set() above
    >>> a
    ['Blah', 'Hello']
    

    Check that you didn't overwrite list by accident:

    >>> assert list == __builtins__.list
    
    0 讨论(0)
  • 2020-12-22 19:13

    This will work:

    >>> t = [1,1,2,2,3,3,4,5]
    >>> print list(set(t))
    [1,2,3,4,5]
    

    However, if you have used "list" or "set" as a variable name you will get the:

    TypeError: 'set' object is not callable
    

    eg:

    >>> set = [1,1,2,2,3,3,4,5]
    >>> print list(set(set))
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: 'list' object is not callable
    

    Same error will occur if you have used "list" as a variable name.

    0 讨论(0)
  • 2020-12-22 19:13

    Your code works with Python 3.2.1 on Win7 x64

    a = set(["Blah", "Hello"])
    a = list(a)
    type(a)
    <class 'list'>
    
    0 讨论(0)
提交回复
热议问题