x = set(x for name,x in marksheet)
First, the x
on the right has nothing to do with the x
on the left. I'll call the one on the right x_i
to distinguish them.
set
: We're going to make a Python set
. A set
is a container (like a list) with the rule that each item may only appear once.
x_i for name,x_i in marksheet
: This is a generator expression (like a list comprehension). It's a shortcut for doing a for
loop.
name,x_i in marksheet
: This is tuple unpacking. marksheet
looks something like [(name1, x1), (name2, x2), ...]
: it is a list of lists. The name,x_i
there could also be written (name, x_i)
: more explicitly a tuple.
The same code could be written:
x = set([]) # start with an empty set
for name, x_i in marksheet:
x.add(x_i)
So it selects the unique values of the second element of each pair in marksheet
.
Since name
isn't used, it's common to use the dummy variable _
for that. You could use a direct set comprehension, too, instead of a generator expression:
x = {x_i for _, x_i in marksheet}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…