简体   繁体   中英

Python Counter in dict vs list in dict probability of choosing an element

I have a question for Counter with python dictionary. I build dictionary using Counter (it helps me to build adjacency matrix)

{48: {Note(note=48, duration=200): 4, Note(note=52, duration=200): 2}}

I use namedtuple for this example. The values stored 48 - fourfold 52 - double?

Let do this with list in dict:

{48: ['48','48','48','48','52','52']}

Now I will choose a random value from a given key (48). What is the probability for the list in the dictionary and for the dictionary with counter? It's better to do this with list in dictionary? Does it matter?

I wonder the extract of dic with counter give me {48: {48,48,48,48}, {52,52}} or Counter only store number of elements?

The real question is: Which way I should use to get random value from key? Dict with list or Dict with counter? It's the same?

I woring on Markov Chain to generate music. I have set of notes and I build a dictionary.

It depends on how you're randomly selecting the elements.

If you're using random.choice , then you want to use the dict with list values. This is because when you iterate over a Counter you only iterate over the keys, so random.choice(some_counter) weights all keys of some_counter equally.

If you're using Python >= 3.6, you can use the new random.choices to select the keys using their values as weights

from random import choices 
from collections import Counter

counts = Counter('Some input iterable')

print(choices(*zip(*counts.items())))
# This gives us a list containing one randomly selected key of counts
# ['e'] for example
# If you want more, you can specify a keyword argument k equal to the number of elements
#   you  want to select form the population (with replacement)

choices(*zip(*counts.items())) is a shorter way of doing something like

keys = []
values = []
for key, value in counts.items():
    keys.append(key)
    values.append(value)
print(choices(keys, values))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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