下面是解決方案,你的數據存儲的方式 - 使處理很難。
>>> lst = [['Amy,1,"10,10,6"'], ['Bella,3,"4,7,2"'], ['Cendrick,3,"5,1,9"'],
['Fella,2,"3,8,4"'], ['Hussain,1,"9,4,3"'], ['Jamie,2,"1,1,1"'], ['Jack,3,"10,8,0"'], ['Thomas,2,"5,0,5"'], ['Zyra,1,"7,8,7"']]
>>> from itertools import chain
>>> lst_flat = chain.from_iterable(lst)
>>> sorted_lst = sorted(filter(lambda x: x.split(',')[1] == '2', lst_flat))
>>> print map(lambda x: (x.split(',')[0],
max([int(y) for y in x.split('"')[1].split(',')])), sorted_lst)
[('Fella', 8), ('Jamie', 1), ('Thomas', 5)]
你應該考慮清理你代表你的數據:
>>> from pprint import pprint
>>> from itertools import chain
>>> lst_clean = []
>>> for item in chain.from_iterable(lst):
... name, cls = item.split(',')[0], item.split(',')[1]
... marks = [int(x) for x in item.split('"')[1].split(',')]
... lst_clean.append((name, cls, marks))
>>> pprint(lst_clean)
[('Amy', '1', [10, 10, 6]),
('Bella', '3', [4, 7, 2]),
('Cendrick', '3', [5, 1, 9]),
('Fella', '2', [3, 8, 4]),
('Hussain', '1', [9, 4, 3]),
('Jamie', '2', [1, 1, 1]),
('Jack', '3', [10, 8, 0]),
('Thomas', '2', [5, 0, 5]),
('Zyra', '1', [7, 8, 7])]
>>> sorted_lst = sorted([(name, cls, marks) for (name, cls, marks) in lst_clean if cls == '2'])
>>> for name, cls, marks in sorted_lst:
... print name, max(marks)
Fella 8
Jamie 1
Thomas 5
好了,感謝您的反饋 – Hussain
我沒有注意到每一個元素是一個字符串。我編輯我的解決方案。 – user162988
你在變換函數裏面的「輸入」是什麼意思 - 當我調用函數時,我應該把列表的名字放在這裏嗎? – Hussain