You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python实现列表构成的矩阵按名称最大间距排序?

Python实现:让数据矩阵中相同名称行尽可能间隔最远的排序

此前该问题曾被讨论过,分别寻求Excel和Python的解决方案,不过已有方案均不适用于真实场景,因此编写了这段Python代码分享给大家,欢迎评论、批评和改进。代码中包含大量print语句,仅用于更清晰地展示执行步骤,目前多次测试表现良好。

import datetime

matrix = [[True, 'Tricha', 6, 'country', 'state', 'city', 'username', datetime.datetime(2020, 10, 25, 21, 0), 'comment'], [True, 'Joe', 6, 'country', 'state', 'city', 'username', datetime.datetime(2020, 10, 25, 21, 0), 'comment'], [True, 'July', 6, 'country', 'state', 'city', 'username', datetime.datetime(2020, 10, 25, 21, 0), 'comment'], [True, 'John', 8, 'country', 'state', 'city', 'username', datetime.datetime(2020, 10, 25, 21, 0), 'comment'], [True, 'John', 8, 'country', 'state', 'city', 'username', datetime.datetime(2020, 10, 25, 21, 0), 'comment'], [True, 'John', 8, 'country', 'state', 'city', 'username', datetime.datetime(2020, 10, 25, 21, 0), 'comment'], [True, 'Mary', 7, 'country', 'state', 'city', 'username', datetime.datetime(2020, 10, 25, 21, 0), 'comment'], [True, 'Mary', 7, 'country', 'state', 'city', 'username', datetime.datetime(2020, 10, 25, 21, 0), 'comment'], [True, 'Mike', 9, 'country', 'state', 'city', 'username', datetime.datetime(2020, 10, 25, 21, 0), 'comment'], [True, 'Mike', 9, 'country', 'state', 'city', 'username', datetime.datetime(2020, 10, 25, 21, 0), 'comment'], [True, 'Bob', 7, 'country', 'state', 'city', 'username', datetime.datetime(2020, 10, 25, 21, 0), 'comment']]


column_to_sort = 1  # 用于排序的列索引

lista = []

for item in matrix:
    lista.append(item[column_to_sort])

print(lista)


lista2 = []


for name in lista:
    if name not in lista2:
        lista2.append(name)

print(lista2)

dic = {}
for item in lista2:
    dic[item] = 0
    print(item)

print(f'dic with quantity equal to zero: {dic}')


for name in lista:
    n = dic[name]
    n = n + 1
    dic[name] = n

print(f'dic: {dic}')

# 根据出现次数对名称排序
dic2 = sorted(dic.items(), key=lambda x: x[column_to_sort])

print(f'dic2: {dic2}')

matrix2 = []


len_matrix = len(matrix)

for g in range(1, len_matrix+1):
    print(f'g: {g}')
    for item in dic2:
        if item[column_to_sort] == g:
            position = 0
            for i in range(0, len_matrix):
                print(f'i: {i}')
                print(f'g: {g}     matrix2 len: {len(matrix2)}')
                if item[0] == matrix[i][column_to_sort]:
                    print(f'Go to position: {position} for {matrix[i]}')
                    matrix2.insert(position, matrix[i])
                    position = int(position + len(matrix2) / g) + 1


print(f'matrix2: {matrix2}')

这段代码可用于数字信息供应商轮换场景:如果某一供应商(对应矩阵中的“名称”列)出现故障,切换到其他供应商后,能尽可能晚地再次选择该故障供应商,为其留出足够的修复时间。

内容的提问来源于stack exchange,提问作者Nanno

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 18:31:02