簡體   English   中英

Python代碼逐行含義

[英]Python Code line by line meaning

我有一個代碼,需要逐行獲取此 python 代碼的含義。

marksheet = []
for i in range(0,int(input())):
    marksheet.append([raw_input(), float(input())])

second_highest = sorted(list(set([marks for name, marks in marksheet])))[1]
print('\n'.join([a for a,b in sorted(marksheet) if b == second_highest]))

我強烈建議您通過python 教程轉到 go

只是為了您對這段代碼的理解,我添加了注釋。

#initialising an empty list!
marksheet = [] 

#iterating through a for loop starting from zero, to some user input(default type string) - that is converted to int
for i in range(0,int(input())): 
    #appending user input(some string) and another user input(a float value) as a list to marksheet
    marksheet.append([raw_input(), float(input())]) 

#[marks for name, marks in marksheet] - get all marks from list
#set([marks for name, marks in marksheet]) - getting unique marks
#list(set([marks for name, marks in marksheet])) - converting it back to list
#sorting the result in decending order with reverse=True and getting the value as first index which would be the second largest.
second_highest = sorted(list(set([marks for name, marks in marksheet])),reverse=True)[1] 

#printing the name and mark of student that has the second largest mark by iterating through the sorted list.
#If the condition matches, the result list is appended to tuple  -`[a for a,b in sorted(marksheet) if b == second_highest])` 
#now join the list with \n - newline to print name and mark of student with second largest mark
print('\n'.join([a for a,b in sorted(marksheet) if b == second_highest]))

希望能幫助到你!

會在評論中這樣做,但我還沒有 50 的聲譽:

您不需要在 second_highest 上使用 sorted 但顯然依賴它不是一個好習慣所以您可以保持排序。 在已經排序的列表上調用 sorted 無論如何都不會使用很多資源。

second_highest = sorted(list(set([marks for name, marks in marksheet])))[1]

此外,如果列表包含類似 [1,3,2,5,3,2,1] 的內容,它將給出 2 作為結果而不是 1,因為集合刪除了所有重復項。

如果要保留重復項,請使用:

second_highest = sorted([marks for name, marks in marksheet]))[1]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM