本文介绍了随机整理然后重新整理python列表的一种好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以可以说我有一个元组列表

So lets say i have a list of tuples

l=[(1,2),(3,4),(5,6),(7,8),(9,10)]

我想按照特定规则对值进行混排,以便在对列表进行混排后可以使用相同的方法将其重新混排.

I want to shuffle the values after a specific rule, so that after i shuffle the list i can unshuffle it back using the same method.

一个例子是,我将整个列表向右移动1个位置,然后我可以将混洗后的列表向左移动一个位置,这样我就可以获得原始列表.

One example would be that i shift the entire list to the right with 1 position and then i can shift the shuffled list with one position to the left so i can get the original list.

但这似乎很简单,所以我想知道他们是否是更具创意的方法

But this seems kinda simple so i was wondering if they're more creative methods of doing this

我的想法是,如果我向某人发送经过改组的列表,他可以不了解原始列表而只知道用于改组的方法来对其进行改组

The idea would be that if i send someone the shuffled list, he could unshuffle it without knowing the original list,only knowing the method used for shuffle

推荐答案

您可以选择某种算法来确定可从列表本身派生且不依赖于其顺序的种子.

You could choose some algorithm to determine a seed that can be derived from the list itself and does not depend on its order.

对于示例数据结构,种子可以例如是所有值的总和.然后,使用该种子,您将生成数字从0到n-1的随机(但确定性)排列.然后,该排列可以用作随机播放和取消随机播放功能的基础:

For the example data structure, the seed could for instance be the sum of all values. Then with that seed you would generate a random (but deterministic) permutation of the numbers from 0 to n-1. That permutation can then be used as a basis for the shuffle and unshuffle functions:

import random

def getperm(l):
    seed = sum(sum(a) for a in l)
    random.seed(seed)
    perm = list(range(len(l)))
    random.shuffle(perm)
    random.seed() # optional, in order to not impact other code based on random
    return perm

def shuffle(l):
    perm = getperm(l)
    l[:] = [l[j] for j in perm]

def unshuffle(l):
    perm = getperm(l)
    res = [None] * len(l)
    for i, j in enumerate(perm):
        res[j] = l[i]
    l[:] = res

示例调用:

l=[(1,2),(3,4),(5,6),(7,8),(9,10)]
print(l)
shuffle(l)
print(l) # shuffled
unshuffle(l)
print(l)  # the original

这篇关于随机整理然后重新整理python列表的一种好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 19:24