Home > OS >  How can I create a new list with random words of another list, while keeping the same amount that I
How can I create a new list with random words of another list, while keeping the same amount that I

Time:11-03

He Guys,

i need to counter balance my words for an experiment in Python. As I am a bit new in Python, I don't know how to solve the following problem:

Function:

import random
def counterbalance(wordlist):
    count = 0
    wordlist_new = []
    for word in wordlist:
        wordlist_new.append(random.choice(wordlist))
        count  = 1
        if count == 0:
            break
    return wordlist_new
 
wordlist = ["Bati", "Uteli", "Foki", "Ipe", "Asemo", "Ragi", "Bilu", "Oga", "Egi", "Tidu", "Pewo", "Elebo", "Dalo", 
            "Bofe","Tari", "Zega", "Atesi", "Teku", "Doza", "Bani"]

print(counterbalance(wordlist))

I want 10 words in a new list that differ from each other and I need to do this 6 times. There can only be no duplicates in the new list of words. So no "Bati" and "Bati" in the same list.

CodePudding user response:

You can use numpy.random.choice with replace=False:

import numpy as np
def counterbalance(wordlist):
    return list(np.random.choice(wordlist,10,replace=False))

>>> counterbalance(wordlist)
['Tidu',
 'Teku',
 'Bani',
 'Doza',
 'Oga',
 'Zega',
 'Asemo',
 'Egi',
 'Elebo',
 'Bofe']

CodePudding user response:

You want 10 words from a created list. We'll use for loop which will run 10 times. Then we'll use random.choice() function to get random element from list and add it in the empty list. After this we'll remove the random element from the created list so that we won't get the same element again. This process will go on 10 times and then return new list. Your code:

import random
def counterbalance(wordlist):
    new_list=[]
    for i in range(10):
        x=random.choice(wordlist)
        new_list.append(x)
        wordlist.remove(x)
    return new_list
print(counterbalance(["Bati", "Uteli", "Foki", "Ipe", "Asemo", "Ragi","Bilu","Oga","Egi", "Tidu", "Pewo", "Elebo", "Dalo", "Bofe","Tari","Zega", "Atesi", "Teku", "Doza", "Bani"]))
  • Related