首页 > 解决方案 > 按随机生成的权重对元组进行排序

问题描述

问题: 我有一个包含字符串和 int 的元组列表。我已经使用内置的 sorted 函数和 lambda 按第二个值对元组进行了排序。问题是我还需要对元组进行分组,以防它们具有相同的 int。在将它们分组排序后,我需要生成一个介于 1 和 6 之间的随机数,并根据最高值将相应的元组放入最终列表中,该列表旨在表示真正排序的元组。

上下文:该算法旨在成为角色扮演游戏的倡议滚轮,将一个值与下一个值进行比较是不够的,所有具有相同 int 值的元组都需要同时比较,而不是一个接一个。

当前代码:

iniList = [('Enemy 3', 15), ('Aldare', 14), ('Enemy 2', 14), ('Enemy 5', 14), ('Enemy 1', 13), ('Enemy 4', 13)]
finalIniList = [] #the list meant to contain the tuples when they are sorted
iniGroups = []
    currentIni = iniList[0][1]
    currentIniGroup = []
    finalIniList = []
    for x in range(len(iniList)):
        if(currentIni == iniList[x][1]):
            currentIniGroup.append(iniList[x])
            if(x == len(iniList) - 1): iniGroups.append(currentIniGroup)
        else:
            iniGroups.append(currentIniGroup)
            currentIniGroup = []
            currentIniGroup.append(iniList[x])
            currentIni = iniList[x][1]
            if(x == len(iniList) - 1): iniGroups.append(currentIniGroup)
for item in iniGroups:
        print(item)

输出:

[('Enemy 3', 15)]
[('Aldare', 14), ('Enemy 2', 14), ('Enemy 5', 14)]
[('Enemy 1', 13), ('Enemy 4', 13)]

标签: pythonsortingtuples

解决方案


给定

iniList = [('Enemy 3', 15), ('Aldare', 14), ('Enemy 2', 14), ('Enemy 5', 14), ('Enemy 1', 13), ('Enemy 4', 13)]

使用itertools.groupbyrandom.sample

from random import sample
from itertools import groupby

finalIniList = [(group[0],
                 sample(list_:=[tup[0] for tup in group[1]],k=len(list_)),
                )
                for group in groupby(iniList,key=lambda tup: tup[1])
               ]

得到类似的东西

>>> finalIniList
[
 (highest_initiative, ['shuffled', 'list', 'of', 'entities']),
 (lower_initiative,   ['entity']),
 (lowest_initiative,  ['some', 'more', 'entities', 'randomly', 'ordered']),
]

推荐阅读