Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - what means "x=sorted(list(set(x for name,x in marksheet)))" in this code

marksheet=[]
marksheet = [[input(), float(input())] for _ in range(int(input()))]
        

x=sorted(list(set(x for name,x in marksheet)))
print(x)

I've just started studying python,I'm not understand the "set(x for name,x in marksheet)" part.What is mean of that ?

question from:https://stackoverflow.com/questions/65923876/what-means-x-sortedlistsetx-for-name-x-in-marksheet-in-this-code

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

1 Reply

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

  1. 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.

  2. 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.

  3. 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}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...