I have the following list:
original_list = [('Anger', 'Envy'), ('Anger', 'Exasperation'), ('Joy', 'Zest'), ('Sadness', 'Suffering'), ('Joy', 'Optimism'), ('Surprise', 'Surprise'), ('Love', 'Affection')]
I am trying to create a random
list comprising of the 2nd element of the tuples (of the above list) using the random
method in such a way that duplicate values appearing as the first element are only considered once.
That is, the final list I am looking at, will be:
random_list = [Exasperation, Suffering, Optimism, Surprise, Affection]
So, in the new list random_list
, strings Envy
and Zest
are eliminated (as they are appearin the the original list twice). And the process has to randomize the result, i.e. with each iteration would produce a different list of Five elements.
May I ask somebody to show me the way how may I do it?
CodePudding user response:
d={} # an empty dictionary
original_list = [('Anger', 'Envy'), ('Anger', 'Exasperation'), ('Joy', 'Zest'), ('Sadness', 'Suffering'), ('Joy', 'Optimism'), ('Surprise', 'Surprise'), ('Love', 'Affection')]
for y in original_list:
d[y[0]]=y[1]
print(d)
#{'Anger': 'Exasperation', 'Joy': 'Optimism', 'Sadness': 'Suffering', 'Surprise': 'Surprise', 'Love': 'Affection'}
random_list=[x for x in d.values()]
output
#['Exasperation', 'Optimism', 'Suffering', 'Surprise', 'Affection']
CodePudding user response:
You can use dictionary to filter the duplicates from original_list
(shuffled before with random.sample
):
import random
original_list = [
("Anger", "Envy"),
("Anger", "Exasperation"),
("Joy", "Zest"),
("Sadness", "Suffering"),
("Joy", "Optimism"),
("Surprise", "Surprise"),
("Love", "Affection"),
]
out = list(dict(random.sample(original_list, len(original_list))).values())
print(out)
Prints (for example):
['Optimism', 'Envy', 'Surprise', 'Suffering', 'Affection']