Reputation: 898
I'm trying to make it so I get random choice out of an list of players... It's fairly simple, I know, but I can't get it to work, I get some random letters, like "i" or "e" as result :O
Here's that part of code:
print "p.getName()", p.getName()
randomtarget = choice(p.getName())
p is a list of players, getName is function to get their names, I get them successfully, so this is what I got:
22:29:21 [INFO] p.getName() Brixishuge
22:29:21 [INFO] Random target: i
obviously, random target should be "Brixishuge", since it's only possible target, but I get "i" as result, why? What am I doing wrong?
Thanks in advance!
Upvotes: 2
Views: 8123
Reputation: 4425
Your input to choice must be a list so that you will return one of the elements of that list. Here you are putting in a string so that choice will return one of the characters of that string.
import random
p = ['Brixishuge', 'user2971511', 'sabbahillel']
random.choice(p)
If your input was ['Brixishuge'] it would work the way you expect.
Description The method choice() returns a random item from a list, tuple, or string.
Syntax Following is the syntax for choice() method:
choice( seq ) Note: This function is not accessible directly, so we need to import random module and then we need to call this function using random static object.
Parameters seq -- This could be a list, tuple, or string...
Return Value This method returns a random item.
Upvotes: 2
Reputation: 620
random.choice takes a list of things to choose from.
Since you are giving it just a string (p.getName()
returns a string) it is treating the string
as a list of characters, from which it is choosing a character ('i' in your case.)
You probably meant this:
randomtarget = choice([p.getName()])
You can make a list either by putting something in square brackets or by calling the list function.
l = [p.getName()]
l = list(p.getName())
Apon further reading, it apears that p is not a list of players but one single player.
If you want the name of a random player you should try this:
player = choice(list_of_players)
name = player.getName()
Upvotes: 4