按随机生成的权重对元组进行排序

Sorting tuples by randomly generated weight

问题: 我有一个包含字符串和整数的元组列表。我已经使用内置的排序函数和 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)]

给出

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

使用itertools.groupby and random.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']),
]

After they are sorted in groups I need to generate a random number between 1 and 6 and based on the highest put the corresponding tuple inside a final list which is meant to represent the truly sorted tuples.

如果两个项目随机生成的数字相同,您如何打破平局?

如果您对在组内简单地随机均匀排序感到满意,您可以执行以下操作:

import random

def sort_with_grouping(ll):
    n = len(ll)
    idx_list = list(range(n))
    random.shuffle(idx_list)
    ll_with_idx = [(s, i, i*n + idx)for (s, i), idx in zip(ll, idx_list)]
    ll_with_idx.sort(key=lambda t: -t[2])
    
    return [(s, i) for (s, i, _) in ll_with_idx]

只要列表长度的平方小于最大整数,我怀疑这会是个问题。如果需要,您可以为随机数生成器设置种子。