2011-09-18 7 views
0

を解析マイファイルは次のようになります100によって2のパイソン:テキストファイル

マトリックス、

Iは、各行の最初の要素に対応する各列つのリストのためのリストを作成したいです電流にマッピングし、第2の要素は温度にマッピングする。

以下に示すとおりです。コードを見栄え良くするためのよりよい方法はありますか?ジェネレータ式の使用

-12,30 
-34,50 
-33,89 
-900,9 
-2,37 
-7,17 
-8,28 
-12,30 
-34,50 
-33,89 

def parse_log(fname): 
    f = open(fname, "r") 
    samples = f.readlines() 
    samples = filter(lambda x: not x.startswith('*'), samples) 
    print(samples) 
    current = map(lambda x: -1 * int(x.split(',')[0]), samples) 
    print(current) 
    temperature = map(lambda x: int(x.split(',')[1]), samples) 
    print(temperature) 
    return (current, temperature) 
+0

'' lambda 'で '' map''と '' filter''を避けてください。理解を使用する。 – JBernardo

答えて

0

def parse_log(fname): 
    with open(fname, "r") as file: 
     return zip(*(
      (int(current) * -1, int(temp)) for current, temp in 
       (line.strip().split(',') 
        for line in file if not line.startswith('*')) 
     )) 

print parse_log(filename) 

[(-12, -34, -33, -900, -2, -7, -8, -12, -34, -33), (30, 50, 89, 9, 37, 17, 28, 30, 50, 89)] 

警告を、それは読んで何が起こっているか理解することはおそらく困難だとして、これは必ずしも良いとは限りません。ドキュメントストリングで正しく文書化してください。ライン毎に二回splitコールを行うことを避けるために

+0

あなたの答えはリスト内包表記を使用していません。あなたはまた、電流の負の値を修正することを忘れました。 – agf

+0

申し訳ありませんが、私の答えは変更されましたが、私のテキストは変更されていません。テキストを修正しました:) – six8

+0

ああ、彼は彼の要求にそれを入れなかったので、私はコードでそれを見落としました。 – six8

1

、私は以下のソリューション

def parse_log(fname): 
    with open(fname) as f: 
     samples = [line.strip() for line in f.readlines() 
        if not line.startswith('*')] 
     ints = [map(int, line.split(",")) for line in samples] 
     currents = [-x[0] for x in ints] 
     temperatures = [x[1] for x in ints] 
     return currents, temperatures 
1

をお勧めしたいこれは、ログファイルの数メガバイトまでのIMO合理的である、単純なバージョンである(それはdoesnのメモリ使用量や解析中の計算時間を最小限に抑えよう):

def parse_log(fname): 
    data = [map(int, x.split(",")) for x in open(fname) if x[:1] != "*"] 
    return ([-current for current, temp in data], 
      [temp for current, temp in data])