python - 嵌套列表中的唯一值 - 随机

标签 python python-3.x nested-lists

我有一个基本上可以工作的程序,它创建由用户设置的大小的嵌套列表,并根据用户输入重复。

但是,我希望各个集合仅包含唯一值,目前这是我的输出。

> python3 testv.py 
Size of your Range?: 12
Size of your Sets?: 3
How many sets?: 4
[['Two', 'Seven', 'Five'], ['Four', 'Six', 'Two'], ['Three', 'Five', 'Thirteen'], ['Six', 'Two', 'Two']]

这是我的程序,x 是我的列表理解,用于创建嵌套列表,是否有一个好的方法来定义它以保持值的唯一性。

import random


class WeightedRandomizer:

    def __init__(self, weights):
        self.__max = .0
        self.__weights = []
        for value, weight in weights.items():
            self.__max += weight
            self.__weights.append((self.__max, value))

    def random(self):
        r = random.random() * self.__max
        for ceil, value in self.__weights:
            if ceil > r:
                return value


range_size = 0
if range_size == 0:
    try:
        rSize = int(input('Size of your Range?: '))
        setSize = int(input('Size of your Sets?: '))
        numSets = int(input('How many sets?: '))
    except ValueError:
        print('That was not an integer!')
        range_size = 0


base_value = 100 / rSize
num_weighted = [base_value] * rSize
num_weighted[0] = round(base_value * 2.2, 1)
num_weighted[1] = round(base_value * 1.8, 1)
num_weighted[2] = round(base_value * 1.8, 1)
num_weighted[3] = round(base_value * 1.5, 1)
num_weighted[4] = round(base_value * 1.4, 1)
num_weighted[5] = round(base_value * 1.3, 1)


# redistribute the difference of top 6 and rest of range
top6 = (sum(num_weighted[0:6]))
not_top6 = rSize - 6
pts_alloc = round((100 - top6) / not_top6, 1)

num_weighted[6:] = [pts_alloc for i in range(len(num_weighted) - 6)]

keys = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight',
        'Nine', 'Ten', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen']

dictionary = dict(zip(keys, num_weighted))

wr = WeightedRandomizer(dictionary)

x = [[wr.random() for i in range(setSize)] for j in range(numSets)]

print(x)

最佳答案

将此函数添加到您的类中:

def take(self, amount):
    ret = []
    while True:
        item = self.random()
        if item in ret:
            continue
        ret.append(item)
        if len(ret) == amount:
            return ret

然后将您的列表理解更改为:

x = [wr.take(setSize) for j in range(numSets)]
<小时/>

基本上,答案是获取随机项目,然后存储它们,直到拥有所需数量的独特项目。

<小时/>

应该看起来像这样:

import random


class WeightedRandomizer:

    def __init__(self, weights):
        self.__max = .0
        self.__weights = []
        for value, weight in weights.items():
            self.__max += weight
            self.__weights.append((self.__max, value))

    def take(self, amount):
        ret = []
        while True:
            item = self.random()
            if item in ret:
                continue
            ret.append(item)
            if len(ret) == amount:
                return ret

    def random(self):
        r = random.random() * self.__max
        for ceil, value in self.__weights:
            if ceil > r:
                return value


range_size = 0
if range_size == 0:
    try:
        rSize = int(input('Size of your Range?: '))
        setSize = int(input('Size of your Sets?: '))
        numSets = int(input('How many sets?: '))
    except ValueError:
        print('That was not an integer!')
        range_size = 0


base_value = 100 / rSize
num_weighted = [base_value] * rSize
num_weighted[0] = round(base_value * 2.2, 1)
num_weighted[1] = round(base_value * 1.8, 1)
num_weighted[2] = round(base_value * 1.8, 1)
num_weighted[3] = round(base_value * 1.5, 1)
num_weighted[4] = round(base_value * 1.4, 1)
num_weighted[5] = round(base_value * 1.3, 1)


# redistribute the difference of top 6 and rest of range
top6 = (sum(num_weighted[0:6]))
not_top6 = rSize - 6
pts_alloc = round((100 - top6) / not_top6, 1)

num_weighted[6:] = [pts_alloc for i in range(len(num_weighted) - 6)]

keys = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight',
        'Nine', 'Ten', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen']

dictionary = dict(zip(keys, num_weighted))

wr = WeightedRandomizer(dictionary)

x = [wr.take(setSize) for j in range(numSets)]

print(x)

关于python - 嵌套列表中的唯一值 - 随机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20047875/

相关文章:

python - gensim 的 word2vec 中的图层大小

python - 检查嵌套列表是否在特定索引处具有和不具有值的优雅方法是什么?

python - 修改带有换行符的 BeautifulSoup .string

python - 在 PyDev 编辑器中换行文本

python - 如何在 Flask-SocketIO 中转义 HTML 字符?

python-3.x - TensorFlow 2.5.0 与 NumPy 1.21+ 不兼容? (2021-10-05)

python - 如何通过索引创建新字符串?

python - 使用 numpy 将数组元素添加到矩阵的每一列

SlideUp 的列表选择器中的 jquery 列表

python - 有没有更好的方法来合并具有子列表的元组的项目而不创建如下所示的新函数?