Issue
Can anyone please explain the following statement?
result = sorted(set([score for name, score in alist]))[1]
Where alist
is a nested list as follows:
[[name1, score1], [name2, score2], [name3, score3]]
I understand that sorted()
function makes the contents ordered. set([])
is the data type to store the ordered contents. But [score for name, score in alist]
is the part where I'm unclear.
alist = [[name1, 80], [name2, 99], [name3, 90]]
result = sorted(set([score for name, score in alist]))[1]
I want to understand the statement better.
Solution
[score for name, score in alist]
is a list comprehension, that can be written as follows (using a temporary variable name tmp
here just for example):
tmp = []
for name, score in alist:
tmp.append(score)
print(tmp)
tmp
is a list that will contain only scores from alist
:
[80, 99, 90]
So set([score for name, score in alist])
will create a set from this list (and remove duplicates - if any). The result:
{80, 90, 99}
You then sort the set and get the second element ([1]
):
result = sorted(set([score for name, score in alist]))[1]
result
is now 90
Answered By - Andrej Kesely
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.