简体   繁体   English

试图将加权RNG函数从php转换为python 3,但感到困惑

[英]Trying to translate weighted RNG function from php to python 3 but am confused

Please don't think badly of me for asking, but I really am confused. 请不要对我提出的要求感到不好,但是我真的很困惑。

    <?php
      function getRandomWeightedElement(array $weightedValues) {
        $rand = mt_rand(1, (int) array_sum($weightedValues));

        foreach ($weightedValues as $key => $value) {
          $rand -= $value;
          if ($rand <= 0) {
            return $key;
          }
        }
      }
    ?>

I am trying to translate this function I've used for a long time into Python 3, but don't understand why my Python version sometimes returns more than one key from test1. 我试图将我已经使用很长时间的此功能转换为Python 3,但不明白为什么我的Python版本有时会从test1返回多个键。

    #getRandomWeightedElement
    #Takes in a keyed dictionary and returns a random element
    import random

    def getRandomWeightedElement(**data):
        rand = random.randint(1, sum(data.values()))

        for key, value in data.items():
            rand -= value
            if rand <= 0:
                print(key)

    test1 = {'One':25,'Two':25,'Three':25,'Four':25}

    getRandomWeightedElement(**test1)

So basically I'm asking, why doesn't my function in Python 3 work the same as the function in Php and why does it return multiple keys from test1? 所以基本上我在问,为什么我在Python 3中的功能与PHP中的功能不一样,为什么它从test1返回多个键?

I'm sorry if I'm missing something obvious, I've just started Python and don't yet know how everything operates. 很抱歉,如果我缺少明显的东西,我刚刚启动Python,但还不知道一切如何运行。 Any help I would greatly appreciate. 任何帮助,我将不胜感激。 Please also let me know if I've asked my question incorrectly. 如果我的提问有误,也请告诉我。

In your original PHP code, your function returns the key as soon as rand becomes a non-positive number, but in your Python code, you simply print the key without returning. 在原始的PHP代码中,只要rand变为非正数,函数就会返回键,但是在Python代码中,您只需打印键而无需返回。

You should return the key in your new code also, and print the returning value of the function instead: 您还应该在新代码中返回键,并打印该函数的返回值:

import random

def getRandomWeightedElement(**data):
    rand = random.randint(1, sum(data.values()))

    for key, value in data.items():
        rand -= value
        if rand <= 0:
            return key

test1 = {'One': 25, 'Two': 25, 'Three': 25, 'Four': 25}

print(getRandomWeightedElement(**test1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM