Python - 排序列表的列表

1 投票
1 回答
1990 浏览
提问于 2025-04-16 17:36

大家好,

我可能漏掉了一些明显的东西。

我在创建一个列表的列表(在C++中叫“vector”),然后想用一些字段作为排序的关键字来对里面的列表(“记录”)进行排序。但是这并没有成功。我尝试了两种不同的方法:一种是用“lambda”,另一种是用“itemgetter”。没有出现错误或警告。我到底哪里做错了呢?

//** 我的代码:开始

class 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 main():

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 ['a', 'b', 'c'] ['a', 'b', 'c']

2 ['a', 'c', 'b'] ['a', 'c', 'b']

****

运行得很好。

@Ned Batchelder - 谢谢你。

1 个回答

2

sorted这个函数会返回一个新的排序好的列表。你现在没有把这个值赋给任何东西。可以试试这样:

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

撰写回答