为什么这个理解不起作用?

时间:2012-07-15 00:30:21

标签: python

在Python 2.6.5中,给出了这个列表     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

谢谢。

2 个答案:

答案 0 :(得分:25)

$ 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])

您可以使用显式setgenerator来完成python2.6中的结果:

>>> set(x for x in mylist if mylist.count(x) >= 2)
set([20])

答案 1 :(得分:8)

您使用的是哪个版本的Python?设置理解appeared in 2.7.x+ and 3.x+。如果您使用的是旧版本,则会获得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

Python 2.7.x + / 3.x +的情况并非如此:

>>> {x for x in mylist if mylist.count(x) >= 2}
set([20])