Python - 列表的排序列表

发布于 2024-11-07 11:44:28 字数 2138 浏览 0 评论 0原文

大家好 我可能遗漏了一些明显的内容:

创建列表列表(用 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 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 - 谢谢

Hi all
I am probably missing something obvious

Creating list of lists (in C++ notation "vector\\>"), then trying to sort inner lists ("records") using some of the fields as a sort keys. And it would not work. Tryed two different version: with "lambda" and with "itemgetter". There is no error or warning. What am I doing wrong?

//** my code: start

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']

****

Working fine.

@Ned Batchelder - thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

寄人书 2024-11-14 11:44:28

sorted 返回新的排序列表。您没有将值分配给任何东西。尝试:

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

sorted returns the new sorted list. You aren't assigning the value to anything. Try:

self.mx = sorted(self.mx, key=itemgetter(5))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文