lundi 24 août 2020

Python 3 Randomized Selection from Existing List

I have put together the following code in Python 3. The intention is to pull 5 random elements from the list and then to concatenate a string of the 5 elements together. The code works, but the means of randomly selecting the 5 elements is hugely clunky. I am sure that there is a more elegant way to do it, but can't find a better way. Any help on improving would be fantastic Thanks

import random

clean = ["We're the ship without a storm", 'The cold without the warm', 'Light inside the darkness', 
                'That it needs, yeah', "We're a laugh without tear", 'The hope without the fear', 'We are coming, home', 
                "We're off to the witch", 'We may never, never, never, come home', "But the magic that we'll feel", 
                'Is worth the lifetime', "We're all born upon the cross", "We're the throw before the toss", 
                'You can release yourself', 'But the only way is down', "We don't come alone", 'We are fire, we are stone', 
                "We're the hand that writes", 'Then quickly moves away', "We'll know for the first time", 
                "If we're divine"]

#Create a list of randomly selected sentences from the clean list
randomz = []
i = random.randint(0, len(clean)-1)
randomz.append(clean[i])
i = random.randint(0, len(clean)-1)
randomz.append(clean[i])
i = random.randint(0, len(clean)-1)
randomz.append(clean[i])
i = random.randint(0, len(clean)-1)
randomz.append(clean[i])
i = random.randint(0, len(clean)-1)
randomz.append(clean[i])

#Concatenate the selected elements into single string
strg = ''
for x in randomz:
    strg += x + '.' + ' '
    
print(strg)



Aucun commentaire:

Enregistrer un commentaire