1. 程式人生 > >同時對資料做轉換和換算

同時對資料做轉換和換算

1.如果需要對資料進行換算,例如sum(),min(),max(),但是首先得對資料做轉換和篩選,,有一個很優雅的方式解決

score= [5, 7, 18, 19, 29, 39, 40, 41, 51, 57]
s=sum(x*x for x in score)
print(s)

2.實際應用於一些題目測評答案分值的計算

answer={
    "1":0,
    "2":1,
    "3":0,
    "4":1,
    "5":0,
    "6":1,
    "7":0,
    "8":1,
    "9":0,
    "10":1,
    "11":0,
    
"12":1, "13":0, "14":1, "15":0, "16":1, "17":0, "18":1, "19":0, "20":1, "21":0, "22":1, "23":0, "24":1, "25":0, "26":1, "27":0, "28":1, "29":0, "30":1, "31":0, "32":1, "33":0, "34":1, "35":0, "36":1, "37":0, "38
":1, "39":0, "40":1, "41":0, "42":1, "43":0, "44":1, "45":0, "46":1, "47":0, "48":1, "49":0, "50":1, "51":0, "52":1, "53":0, "54":1, "55":0, "56":1, "57":0, "58":1, "59":0, "60":1 } testQuestions= [{'_id': '常規型(C)', 'score': [5, 7, 18, 19, 29, 39, 40, 41, 51, 57], '
max': 10}, {'_id': '社會型(S)', 'score': [1, 12, 15, 26, 27, 37, 45, 52, 53, 59], 'max': 10}, {'_id': '企業型(E)', 'score': [3, 11, 16, 24, 25, 28, 35, 38, 46, 60], 'max': 10}, {'_id': '研究型(I)', 'score': [6, 8, 20, 21, 30, 31, 42, 55, 56, 58], 'max': 10}, {'_id': '現實型(R)', 'score': [2, 13, 14, 22, 23, 36, 43, 44, 47, 48], 'max': 10}, {'_id': '藝術型(A)', 'score': [4, 9, 10, 17, 32, 33, 34, 49, 50, 54], 'max': 10}] #需求是對testQuestions列表中score列表中題號找到answer中對應的值,計算出_id 的總分數,說明白點就是算_id 的分值,現在我的score欄位只是存著題號,要根據題號,去answer中找到分數累加, #我的方法阿是: for item in testQuestions: s=sum(answer[str(x)] for x in item["score"]) print(s) item["score"]=s #輸出結果testQuestions:{'_id': '常規型(C)', 'score': 2, 'max': 10}, {'_id': '社會型(S)', 'score': 3, 'max': 10}, {'_id': '企業型(E)', 'score': 6, 'max': 10}, {'_id': '研究型(I)', 'score': 7, 'max': 10}, {'_id': '現實型(R)', 'score': 6, 'max': 10}, {'_id': '藝術型(A)', 'score': 6, 'max': 10}]