Why doesn't this set comprehension work?

前端 未结 2 569
时光取名叫无心
时光取名叫无心 2020-12-17 16:06

In Python 2.6.5, given this list mylist = [20, 30, 25, 20]

Why does this set comprehension not work?

>>> {x for x in mylist if mylist.co         


        
相关标签:
2条回答
  • 2020-12-17 16:12

    What version of Python are you using? Set comprehensions appeared in 2.7.x+ and 3.x+. If you're using an older version, you'll get a SyntaxError: invalid syntax:

    >>> {x for x in mylist if mylist.count(x) >= 2}
      File "<stdin>", line 1
        {x for x in mylist if mylist.count(x) >= 2}
             ^
    SyntaxError: invalid syntax
    

    That is not the case with Python 2.7.x+ / 3.x+ :

    >>> {x for x in mylist if mylist.count(x) >= 2}
    set([20])
    
    0 讨论(0)
  • 2020-12-17 16:20
    $ python2.6
    >>> mylist = [20, 30, 25, 20]
    >>> {x for x in mylist if mylist.count(x) >= 2}
      File "<stdin>", line 1
        {x for x in mylist if mylist.count(x) >= 2}
             ^
    SyntaxError: invalid syntax
    
    $ python2.7
    >>> mylist = [20, 30, 25, 20]
    >>> {x for x in mylist if mylist.count(x) >= 2}
    set([20])
    

    You can accomplish the results in python2.6 using an explicit set, and a generator:

    >>> set(x for x in mylist if mylist.count(x) >= 2)
    set([20])
    
    0 讨论(0)
提交回复
热议问题