Reputation: 33
I have a function that wants to seperate one list to 2 lists with same length and random list items
code:
def playersorting(playerslist):
random.shuffle(playerslist)
cut = random.randint(0, len(playerslist))
list_1 = playerslist[:cut]
list_2 = playerslist[cut:]
print(list_1)
print(list_2)
playerslist = ['amin', 'hasan', 'reza', 'mohsen', 'alireza', 'mahdi', 'daniyal', 'komeil']
playersorting(playerslist)
output is like:
['mohsen', 'hasan', 'mahdi', 'daniyal', 'reza', 'alireza']
['amin', 'komeil']
['daniyal', 'amin', 'komeil', 'reza', 'mahdi', 'hasan', 'alireza', 'mohsen']
[]
but I want it to be like this:
['daniyal', 'reza', 'hasan', 'alireza']
['komeil', 'mahdi', 'mohsen', 'amin']
random with same length
Upvotes: 1
Views: 53
Reputation: 27557
One way is to use [random.sample()][1]
:
from random import sample
def playersorting(playerslist):
list_1 = sample(playerslist, len(playerslist) // 2)
list_2 = [player for player in playerslist if player not in list_1]
print(list_1)
print(list_2)
playerslist = ['amin', 'hasan', 'reza', 'mohsen', 'alireza', 'mahdi', 'daniyal', 'komeil']
playersorting(playerslist)
Explanation:
random.sample()
takes in an array, population
, and a number, k
, and returns a new array of length k
of randomly selected elements from the array population
.
So sample(playerslist, len(playerslist) // 2)
returns an array of length len(playerslist) // 2
of randomly selected elements from playerslist
.
[player for player in playerslist if player not in list_1]
returns every element in playerslist
that is not already inside the first half of random elements.
Though the random.shuffle()
method is advised.
Upvotes: 2
Reputation: 701
randint
just return a integer value ranged from [0,len(playerslist))
, so use cut
to slice the list will ends with random two different length.
Simplely, you can just:
def playersorting(playerslist):
random.shuffle(playerslist)
cut = int(len(playerslist) / 2)
list_1 = playerslist[:cut]
list_2 = playerslist[cut:]
print(list_1)
print(list_2)
Upvotes: 0
Reputation: 517
import random
def playersorting(playerslist):
random.shuffle(playerslist)
list_1 = playerslist[0:4]
list_2 = playerslist[4:8]
print(list_1)
print(list_2)
playerslist = ['amin', 'hasan', 'reza', 'mohsen', 'alireza', 'mahdi', 'daniyal', 'komeil']
playersorting(playerslist)
Upvotes: 0
Reputation: 9047
Seems you need to change your cut
variable
import random
l = ['amin', 'hasan', 'reza', 'mohsen', 'alireza', 'mahdi', 'daniyal', 'komeil']
half_len = len(l)//2
random.shuffle(l)
l1 = l[:half_len]
l2 = l[half_len:]
print(l1, l2)
['mahdi', 'amin', 'mohsen', 'reza']
['komeil', 'alireza', 'hasan', 'daniyal']
Upvotes: 3