You can use random.choices
from the standard library.
import random
values = ['EV', 'PHEV']
for _ in range(10):
result = random.choices(values, weights=(0.3, 0.7))
print(result[0], end=' ')
Example output: PHEV EV PHEV PHEV PHEV PHEV PHEV PHEV EV EV
Additional info: You're not limited to just 2 options and you can get multiple results.
import random
values = ['A', 'B', 'C']
for _ in range(10):
result = random.choices(values, weights=(1, 4, 10), k=2)
print(result)
Example output:
['B', 'C']
['B', 'C']
['C', 'C']
['C', 'C']
['C', 'B']
['C', 'B']
['B', 'C']
['C', 'C']
['C', 'C']
['B', 'C']
This is a possible implementation including the code from the question. Here I assume that the pev types and their probability are fixed in the code, so I made them an attribute of the class Vehicle
. This can be changed as needed. Note that the distributions are relative and don't have to add up to exactly 1.0
.
import random
class Vehicle:
pev_types = {'EV': 0.3, 'PHEV': 0.7, 'X': 0.2}
def __init__(self):
self.pev_type = self._get_random_pev_type()
def __str__(self):
return f'Vehicle (pev type:{self.pev_type})'
def _get_random_pev_type(self):
return random.choices(list(self.pev_types), weights=self.pev_types.values())[0]
print(', '.join(str(Vehicle()) for _ in range(10)))
Example output:
Vehicle (EV), Vehicle (EV), Vehicle (X), Vehicle (PHEV), Vehicle (PHEV), Vehicle (X), Vehicle (PHEV), Vehicle (PHEV), Vehicle (PHEV), Vehicle (PHEV)