python - 考虑到互斥项目,如何返回洗牌列表?

标签 python python-3.x shuffle

假设我有一个选项列表,我想随机选择一个特定的数字。
就我而言,假设选项在列表中 ['a', 'b', 'c', 'd', 'e']我希望我的脚本返回 3 个元素。
但是,也存在两个选项不能同时出现的情况。也就是说,如果随机选择选项“a”,则不能选择选项“b”。反过来也是如此。
所以有效的输出是:['a', 'c', 'd']['c', 'd', 'b'] , 而诸如 ['a', 'b', 'c'] 之类的东西不会,因为它们同时包含“a”和“b”。
为了满足这些要求,我正在获取 3 个选项和另一个选项以补偿可能的丢弃。然后,我保留了一个 set()使用互斥条件并继续从中删除并检查是否已选择两个元素:

import random


mutually_exclusive = set({'a', 'b'})
options = ['a', 'b', 'c', 'd', 'e']
num_options_to_return = 3

shuffled_options = random.sample(options, num_options_to_return + 1)

elements_returned = 0
for item in shuffled_options:
    if elements_returned >= num_options_to_return:
        break

    if item in mutually_exclusive:
        mutually_exclusive.remove(item)
        if not mutually_exclusive:
            # if both elements have appeared, then the set is empty so we cannot return the current value
            continue

    print(item)
    elements_returned += 1
但是,我可能会过度编码,而 Python 可能有更好的方法来处理这些需求。路过 random 's documentation我找不到开箱即用的方法。有没有比我目前的解决方案更好的解决方案?

最佳答案

一种方法是使用 itertools.combinations 要创建所有可能的结果,过滤掉无效的结果并生成 random.choice 从那:

>>> from itertools import combinations
>>> from random import choice
>>> def is_valid(t):
...     return 'a' not in t or 'b' not in t
... 
>>> choice([
...     t 
...     for t in combinations('abcde', 3) 
...     if is_valid(t)
... ])
... 
('c', 'd', 'e')

关于python - 考虑到互斥项目,如何返回洗牌列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62655830/

相关文章:

java - Collection.shuffle 与种子随机 - 列表大小为 16 的异常

python - datetime => timestamp 的差异仅在某些情况下?

python - 仅在 UNIX 系统上读取文件时出现 UnicodeDecodeError

python - 在 python 中按值删除字典项的最佳方法是什么?

c++ - 修改程序以加密大写和小写输入

java - 如何打乱字符串数组

python - 带条件的嵌套循环中的 lambda

python - 使用 FTP 后端的 Django 文件上传

python - 有没有办法浅复制现有的文件对象?

python - 将整数集合存储在列表中