Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

python - Why doesn't this set comprehension work?

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

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
$ 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])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...