So I have a list and I would like to "assign" the values to a different random value.
For eg.
list = ["dog", "cat", "rat", "bird", "monkey"]
I would like an output like
{"dog": "bird", "cat": "monkey", "rat": "dog", "bird": "rat", "monkey": "cat"}
What I would like is:
I tried this code:
def shuffle_recur(_list):
final = {}
not_done = copy.deepcopy(_list)
for value in _list:
without_list = not_done.copy()
if value in without_list :
without_list.remove(value)
if value in final.values():
for final_key, final_value in final.items():
if final_value == value:
print(final_value, ' ', final_key)
if final_key in without_list :
without_list.remove(final_key)
if len(without_list) < 1:
print('less')
return shuffle_recur(_list)
target = random.choice(without_list)
not_done.remove(target)
final[value] = target
print('{} >> {}'.format(value, target))
return final
But it is very messy and I don't think it the the best way. What would be a better way to do this?
Python's random module provides a sample() function for random sampling, randomly picking more than one element from the list without repeating elements. It returns a list of unique items chosen randomly from the list, sequence, or set. We call it random sampling without replacement.
To use shuffle, import the Python random package by adding the line import random near the top of your program. Then, if you have a list called x, you can call random. shuffle(x) to have the random shuffle function reorder the list in a randomized way. Note that the shuffle function replaces the existing list.
Explanation: In order to pick a single element, randomly, from a given list of elements, choice method is used.
You may just build a random-ordered list of your items, then pair them as key-value
From one hand you'll take the list, in the other hand the same list rotated from on item values[1:] + [values[0]]
, and you zip both to pair 2-by-2 pairs, and build a dict from these pairs
values = ["dog", "cat", "rat", "bird", "monkey"]
shuffle(values)
result = dict(zip(values, values[1:] + [values[0]]))
Example
shuffling gives ['bird', 'dog', 'rat', 'monkey', 'cat']
rotating gives ['dog', 'rat', 'monkey', 'cat', 'bird']
zipping gives [('bird', 'dog'), ('dog', 'rat'), ('rat', 'monkey'), ('monkey', 'cat'), ('cat', 'bird')]
then each pair becomes a mapping
print(values) # ['bird', 'dog', 'rat', 'monkey', 'cat']
print(result) # {'bird': 'dog', 'dog': 'rat', 'rat': 'monkey', 'monkey': 'cat', 'cat': 'bird'}
If you don't the mapping to be following each other, just shuffle
a second time
mappings = list(zip(values, values[1:] + [values[0]]))
shuffle(mappings)
result = dict(mappings)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With