2015-12-11 33 views
-1

我正在從以下格式的文本文件中讀取數據。通過添加新條目來寫入文本文件

1 1 5 
1 3 3 
1 5 4 
2 1 5 
2 4 3 
3 1 2 
3 3 4 
3 4 3 
3 5 4 

第一列表示的coachId,第二列表示playerId,並且最後一列表示由每個教練給每個玩家給出的分數。所以現在說有3名教練和5名球員,我們提供的數據還不完整。我們基本上必須執行一個推薦系統,併爲每個教練產生每個球員缺少的得分。我已經完成了這部分。所以基本上現在我想生成一個輸出文件來填補缺失的分數。這是我的邏輯。

data = np.loadtxt('player.txt') 
coaches = data.T[0] 
players = data.T[1] 
scores = data.T[2] 


a = 0 
total = 3 * 5 #total fields to fill is num of player times num of coaches 

while a < total: 
    b = 0 
    while b < 3: #for each coach 
    #check if score was given 
    # if score is given don't do anything 
    # if score is not given get new socre and write it to file 

我覺得這種方法可能需要很長時間,如果我很多教練和球員。有一個更好的方法嗎?

+0

我懷疑你會先運行一個「GetAllMissingScores」類型的功能,那麼在那些分數分裝,比多得到更好的服務責任1一1循環。您如何設置了很可能會偏好(有可能是一種優化的解決方案,但我不是一個Python的傢伙) – Sitric

+0

http://stackoverflow.com/questions/18689235/numpy-array-replace-nan-values-with - 平均值列 –

+0

@Pardoido這有助於如何? – BlackJack

回答

0

將屬於一起的值分隔爲三個單獨的列表。這使得訪問它們變得更加困難。同樣,如果你想擴展文件,你不需要已經在其中的分數值,但只是教練和球員組合已經在那裏的信息。這可以存儲在set中,以便在組合已經存在的情況下進行高效測試。

外循環似乎正在運行,直到a達到記錄總數?內循環執行每個記錄和每個教練,所以三次三個教練的記錄總數。這沒有什麼意義。

這是一個需要get_score_somehow()填充的方法:

#!/usr/bin/env python 
# coding: utf8 
from __future__ import absolute_import, division, print_function 
from itertools import product 


def main(): 
    filename = 'test.txt' 
    coach_count = 3 
    player_count = 5 

    already_scored = set() 
    with open(filename) as lines: 
     for line in lines: 
      coach_id, player_id, _ = map(int, line.split()) 
      already_scored.add((coach_id, player_id)) 

    with open(filename, 'w') as score_file: 
     for coach_id, player_id in product(
      xrange(coach_count), xrange(player_count) 
     ): 
      if (coach_id, player_id) not in already_scored: 
       score = get_score_somehow(coach_id, player_id) 
       record = [coach_id, player_id, score] 
       score_file.write(' '.join(map(str, record)) + '\n') 


if __name__ == '__main__': 
    main() 
相關問題