0

我有一个包含列表的列表,例如:

table[0] = ['255.255.255.255', '58267', '233', 'ESTABLISHED']
table[1] = ['255.132.0.0', '38367', '273', 'CLOSED']

我想按内部列表对列表“表”进行排序,例如:

我想根据放置在“表”中每个索引中的列表中最后一个索引中的字符串按字母顺序对“表”进行排序。它看起来像这样:

table[0] = ['255.132.0.0', '38367', '273', 'CLOSED']
table[1] = ['255.255.255.255', '58267', '233', 'ESTABLISHED']

他们改变了位置,因为“C”在“E”之前。

我试过这个:

table.sort(key=lambda x: x.sort())
4

2 回答 2

2

尝试这个:

table.sort(key=lambda x: x[-1])

print(table)

输出:

[['255.132.0.0', '38367', '273', 'CLOSED'], ['255.255.255.255', '58267', '233', 'ESTABLISHED']]
于 2020-12-20T19:32:54.297 回答
0

另一种方法是使用numpy'argsort()函数。它按照排序后的顺序返回索引。

import numpy as np
table = [['255.255.255.255', '58267', '233', 'ESTABLISHED'], ['255.132.0.0', '38367', '273', 'CLOSED']]

sorted_indexes = np.argsort([row[-1] for row in table])

sorted_table = np.array(table)[sorted_indexes]
# as list (and not numpy array):
sorted_table.tolist()

# [['255.132.0.0', '38367', '273', 'CLOSED'],
#  ['255.255.255.255', '58267', '233', 'ESTABLISHED']]

但好处np.argsort()是它也适用于 Pandas 数据框:

import pandas as pd
df = pd.DataFrame(table)

sorted_indexes = np.argsort(df.iloc[:, -1])

sorted_df = df.iloc[sorted_indexes, :]

sorted_df                                                                                             

#                  0      1    2            3
# 1      255.132.0.0  38367  273       CLOSED
# 0  255.255.255.255  58267  233  ESTABLISHED

# you can get numpy arrays by `.values`
# and from numpy array to normal lists by `.tolist()
# so:

sorted_df.values.tolist() 

# [['255.132.0.0', '38367', '273', 'CLOSED'],
#  ['255.255.255.255', '58267', '233', 'ESTABLISHED']]

但是 Pandas 当然有内置排序:

df.sort_values(by=[3])

并且您可以给出by几个列名或列索引,它们确定排序的优先列值。使用.values.tolist()您可以将数据框重新转换回简单列表。

于 2020-12-20T20:01:19.593 回答