1. 1用python 寫函數my_index(ch, freq_chs),可求某元素在二維列表中的下
其實這個不難,以下代碼做個參考吧。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#-*-coding:utf-8-*-
class Student(object):
"""
自定義Student類
"""
def __init__(self, name, score):
# 初始化Student,參數name,score
self.name = name
self.score = score
def __cmp__(self, other):
# 重寫比較方法,根據Student類屬性score進行比較
return cmp(self.score, other.score)
def show(self):
return 'name:'+self.name+'; score:'+str(self.score)
def get_input():
name = raw_input('input name > ')
if not name: # 當姓名輸入為空時,返回None
return (None,None)
score = raw_input('input %s\'s score > ' % name)
if name and score:
return (name,int(score)) # 為方便比較,將score強制轉換為int型
else:
return (None,None)
def main():
s_list = []
while True: # 一直循環輸入姓名及成績
name,score = get_input()
if name and score:
s = Student(name, score)
s_list.append(s)
else: # 當輸入姓名或成績為空時跳出循環
break
s_list.sort() # 對Student實體進行排序
for i,s in enumerate(s_list): # 遍歷已經排序的實體列表,並進行顯示
print ' '.join([str(i+1), s.name, str(s.score)])
if __name__ == '__main__':
main()
輸入及輸出結果如下,當然你也可以修改下 s_list 方便測試
1
2
3
4
5
6
7
8
9
10
input name > a
input a's score > 97
input name > b
input b's score > 95
input name > c
input c's score > 96
input name >
1 b 95
2 c 96
3 a 97
注釋已經比較詳細了,應該能看懂。