用Python中的限制改组列表 [英] shuffling a list with restrictions in Python

查看:82
本文介绍了用Python中的限制改组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Python(3)中的限制随机化列表时遇到问题.我还看到了与此有关的其他一些问题,但这些问题似乎都没有真正解决我的问题.我是一个初学者,因此非常感谢您的帮助!

I have a problem with randomizing a list with restrictions in Python (3). I have seen a few other questions relating to this, but none of them really seem to solve my problem. I'm a beginner, so any help is much appreciated!

我正在设计一种使用两种类型的刺激的实验:形状和颜色(每种四个)​​.我需要生成所有16个组合的排列,这是通过random.shuffle-function完成的:

I'm designing an experiment using two types of stimuli: shapes and colors (four of each). I need to generate permutations of all 16 combinations, which I have done with random.shuffle-function:

import random

# letters are shapes, numbers are colors
x=["a1","a2","a3","a4","b1","b2","b3","b4","c1","c2","c3","c4","d1","d2","d3","d4"]

random.shuffle(x)

到目前为止,一切都很好.但是,我想避免形状(字母)或颜色(数字)在结果中连续出现两次(例如,"a2"后跟"a4",或"c2"后跟"a2").

So far so good. However, I want to avoid a shape (letter) or color (number) to appear two times in succession in my result (e.g. "a2" followed by "a4", or "c2" followed by "a2").

有没有办法做这样的限制?
预先感谢!

Is there a way to make such a restriction?
Thanks in advance!

推荐答案

这样的事情应该在合理的时间内给出合理的答案

Something like this should give a reasonable answer in a reasonable time

import random
while 1:
    choices = ["a1", "a2","a3","b1","b2","b3","c1","c2","c3"]

    shuffle = []

    last = ""

    while choices:
        l = choices
        if last:
            l = [x for x in l if x[0] != last[0] and x[1] != last[1]]
        if not l:
            #no valid solution
            break 
        newEl = random.choice(l)
        last = newEl
        shuffle.append(newEl)
        choices.remove(newEl)
    if not choices:
        print(shuffle)
        break

这篇关于用Python中的限制改组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆