2011-05-13 8 views
1

こんにちは、私はおそらく、リストのリストを作成するPythonは -

何かを明らかに行方不明ですすべて リストのリストをソート(C++の表記「ベクター\\>」)、そして(「記録」)を使用して、内側のリストを並べ替えしようとしていますソートキーとしてのフィールドのいくつか。そしてそれはうまくいかないでしょう。 "lambda"と "itemgetter"の2つの異なるバージョンを試しました。エラーや警告はありません。私は間違って何をしていますか?

// * *私のコード:

クラスfwReport開始:* *

def __init__(self): 
    #each field from firewall log file, 17 all together 
    self.fieldnames = ("date", "time", "action", "protocol", \ 
       "src-ip", "dst-ip", "src-port", "dst-port" \ 
       "size", "tcpflags", "tcpsyn", "tcpack", \ 
       "tcpwin", "icmptype", "icmpcode", "info", "path") 
    self._fields = {} 
    self.mx = list() 
    self.dst_ip = collections.Counter() 
    self.src_ip = collections.Counter() 

def openfn(self): 
    try: 
     with open(fn) as f: data = f.read() 
    except IOError as err: 
     raise AssertionError("Can't open %s for reading: %s" % (fn, err)) 
     return 
    #make a matrix out of data, smth. like list<list<field>> 
    #skip first 5 lines (file header) 
    for fields in data.split("\n")[5:25]: 
     temp = fields.split(" ")[:6] #take first 7 fields 
     self.src_ip[temp[4]] += 1 #count source IP 
     self.dst_ip[temp[5]] += 1 #count destination IP 
     self.mx.append(temp) #build list of lists 
    #sorted(self.mx, key=itemgetter(5)) #----> does not work 
    sorted(self.mx, key=lambda fields: fields[5]) #--------> does not work 
    for i in range(len(self.mx)): 
     print(i, " ", self.mx[i][5]) 
    #print(self.dst_ip.most_common(16)) 
    #print(self.src_ip.most_common(16)) 
    print(self.mx[:5][:]) 
    #print(len(self.dst_ip)) 

** ** を** *

DEFメイン():

mx = [["a", "b", "c"], ["a", "c", "b"], ["b", "a", "c"]] 

mx = sorted(mx, key=lambda v: v[1]) 

for i in range(len(mx)): 
    print(i, " ", mx[i], " ", mx[i], end="\n") 

0 'B'、 ''、 'C​​'] [ 'B'、 ''、 'C​​']

1 [ '' ['a'、 'b'、 'c'] ['a'、 'b'、 'c'] ['a'、 'b' B ']

****

ワーキングFiのne。

@Ned Batchelder - 感謝

答えて

2

sortedは新しいソートされたリストを返します。あなたは何かに値を割り当てていません。試してみてください:

self.mx = sorted(self.mx, key=itemgetter(5)) 
+0

doh ...ありがとう! – Nikiton

+1

あなたはまだインプレースでソートすることができます: 'self.mx.sort(key = ...)' – 9000

+0

@ 9000ありがとう、両方の場所とソート(..)の両方が今働いています。私はおそらく精神的なブロックを持っていたでしょう。次回まで... – Nikiton