1
大家好 我可能失去了一些東西明顯Python的 - 排序名單列表
創建名單列表(在C++符號「向量\\>」),然後試圖內部列表進行排序使用(「記錄」)一些字段作爲排序鍵。它不會工作。嘗試了兩種不同的版本:「lambda」和「itemgetter」。沒有錯誤或警告。我究竟做錯了什麼?
// * *我的代碼:啓動
類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', 'A', 'C'] [ 'B', 'A', 'C']
1 [ '一個' , 'b', 'C'] [ 'A', 'b', 'C']
2 [ '一個', 'C', 'b'] [ '一個', 'C',' b']
****
工作音響東北。
@Ned爾德 - 感謝
doh ...謝謝!!! – Nikiton 2011-05-13 22:27:41
您仍然可以在原地進行排序:'self.mx.sort(key = ...)' – 9000 2011-05-13 23:39:25
@ 9000謝謝,無論是就地還是排序(...)現在都在工作。我可能有一個心理障礙。直到下一次... – Nikiton 2011-05-13 23:48:36