Multikey Multivalue Non Deterministic python dictionary

前端 未结 4 1997
清酒与你
清酒与你 2021-02-05 23:08

There is already a multi key dict in python and also a multivalued dict. I needed a python dictionary which is both:

example:

# probabilistically fetch a         


        
4条回答
  •  醉酒成梦
    2021-02-05 23:37

    If it is possible to change the data structure, it would be simpler to have a function returning the data you need. This will be completely flexible and could accommodate any kind of data, should you need to change them later.

    import random
    
    def myfunc(*args):
        if 'red' in args:
            return 'blue'
        elif 'green' in args or 'violet' in args:
            return 'violet'
        else:
            r = random.random()
            if 0 < r < 0.2:
                return 'blue'
            else:
                return 'green'
    
    print(myfunc('green', 'blue'))
    print(myfunc('yellow'))
    

    output (the second line obviously changes):

    violet
    blue
    

提交回复
热议问题