To choose a random element from a list with a specific chance for each element, you can use the following Python code:
import random
def random_choice_with_chances(items):
total_chances = sum(item['result'] for item in items)
chosen_item = None
while chosen_item is None:
random_number = random.randint(1, total_chances)
for item in items:
if random_number <= item['result']:
chosen_item = item
break
return chosen_item
# Example usage:
data = [
{'result': 50, 'emoji': '🦄', 'isNew': False, 'base': ['Volcano', 'Unicorn']},
{'result': 50, 'emoji': '🦄', 'isNew': False, 'base': ['Unicorn', 'Volcano']},
{'result': 50, 'emoji': '🌈', 'isNew': False, 'base': ['Rainbow', 'Hurricane']}
]
# Simulate the random choice
for _ in range(100): # Replace 100 with the number of times you want to simulate
chosen_item = random_choice_with_chances(data)
print(f"Chose {chosen_item['result']}: {chosen_item['emoji']}")
In this code, result is used as the chance for each item to be chosen. The random_choice_with_chances function calculates the total chance for all items and then uses randint to generate a random number. It then iterates over the items, comparing the random number to the result value of each item. The first item whose result is less than or equal to the random number is chosen and the process is repeated for the desired number of times.
Please note that this code assumes that the result values in the list add up to 100 or a multiple of 100, as randint generates a random number between 1 and the specified maximum (exclusive). If you want to choose from a list where the result values do not add up to 100, you would need to normalize the chances and then convert them to a percentage.