python - 按随机生成的权重对元组进行排序
问题描述
问题: 我有一个包含字符串和 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)]
解决方案
给定
iniList = [('Enemy 3', 15), ('Aldare', 14), ('Enemy 2', 14), ('Enemy 5', 14), ('Enemy 1', 13), ('Enemy 4', 13)]
使用itertools.groupby
和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']),
]
推荐阅读
- python - 为什么我在 PyTorch 中用于降噪的自动编码器学会了将所有内容归零?
- c# - 读取 FileStream 超时
- git - ![远程拒绝] master -> master (pre-receive hook denied) git push 错误
- css - 作用域 CSS 选择器性能
- regex - 如何捕获具有逗号和引号的字符串之间的值?
- javascript - React-native 在发出发布请求后得到响应不起作用
- python - 我的消息框代码在我的窗口上不起作用。其他一切正常,但是当我运行它时,我的“关于”消息框不会出现
- python - 如何使用 JSD Cloud API 在 Jira Service Desk 中创建客户?
- cs50 - 如何缩小 CS50 IDE?不小心放大了不知道怎么恢复原来的大小
- html - 没有第三方导入的 Golang 中的 html 渲染器