How to obtain a random string from a list - python

My class was recently introduced to lists and our task is to randomly obtain a name from the said list, This is the code i have generated
import random
Random1 = random.randint(0,7)
Class_List = ['Noah','Simone','Ji Ho','Thanh','Nathanial','Soo','Mickel','Tuan','Thuy Linh']
print (ClassList[{}].format(Random1))
However i receive this error
Traceback (most recent call last):
File "C:/Users/Mickel/Documents/Python/RPS Tournament/Rock Paper Sissor Tornament.py", line 4, in <module>
print (ClassList[{}].format(Random1))
TypeError: list indices must be integers, not dict
Any solutions?

Python has a very simple method for this: random.choice
import random
class_list = ['Noah','Simone','Ji Ho','Thanh','Nathanial','Soo','Mickel','Tuan','Thuy Linh']
print(random.choice(class_list))
Regarding why your answer isn't working:
print (ClassList[{}].format(Random1))
.format is for interpolating a value into a string - for example"{}".format(5). Obviously this is something different than what you're doing. If you wish to still use your approach, here's how:
Class_List = ['Noah','Simone','JiHo','Thanh','Nathanial','Soo','Mickel','Tuan','Thuy Linh']
Random1 = random.randint(0,len(Class_List))
print (ClassList[Random1])

Use random.choice for this. Read the documentation I've linked.

You are printing a value from the list in a form of an empty dictionary where an index number should be instead. That's why you get an error. But you spelled it wrong anyway. It should be "Class_List", not "ClassList".
As for your questing, personally I would do it this way
#!/usr/bin/python
import random
Class_List = ['Noah','Simone','Ji Ho','Thanh','Nathanial','Soo','Mickel','Tuan','Thuy Linh']
random.shuffle(Class_List)
print (Class_List[0])

Related

Don't understand the cause of this AttributeError

What's wrong with that code? When I run it tells me this:
Traceback (most recent call last):
line 24, in <module>
people.append(Dict)
AttributeError: 'str' object has no attribute 'append'
My code:
live = 1
while live == 1:
#reading Database
dataRead = open ("db.txt","r")
if dataRead.read() != " ":
dataRead.close()
people = open ('db.txt','r').read()
do = input ('What Do You Want ? (Search , add) :\n')
#add people
if do == 'add':
#Get The New Data
n_Name = input ('enter the new name:\n')
n_age = input ('enter the new age:\n')
#new Dict
Dict = {'Name:':n_Name,'age':n_age}
people.append(Dict)
#adding people to file
dataWrite = open ("db.txt","w")
dataWrite.write(str(people))
dataWrite.close()
live = 0
The problem is, on line 24, you try to append a dictionary to a string. When you read the db file, it read it as a string. Also the code is really messy and there are a lot better ways to do it. But that's besides the point, the append() method is for lists and the variable "people" is a string, according to your error output.
It says that people is str then it doesn't have an append method. You should just concatenate strings to get them together.
Do:
people += '<append string>'
Have in mind you are trying to append a dictionary to a string. This will throw TypeError cause those type of elements can't be concatenated that way. You should do first: str(dict) to concatenate them.
You're also using a reserved word like dict as a variable. Change it to my_dict or other allowed name.

dynamic variables from list

This is similar to, Python creating dynamic global variable from list, but I'm still confused.
I get lots of flo data in a semi proprietary format. I've already used Python to strip the data to my needs and save the data into a json file called badactor.json and are saved in the following format:
[saddr as a integer, daddr as a integer, port, date as Julian, time as decimal number]
An arbitrary example [1053464536, 1232644361, 2222, 2014260, 15009]
I want to go through my weekly/monthly flo logs and save everything by Julian date. To start I want to go through the logs and create a list that is named according to the Julian date it happened, i.e, 2014260 and then save it to the same name 2014260.json. I have the following, but it is giving me an error:
#!/usr/bin/python
import sys
import json
import time
from datetime import datetime
import calendar
#these are varibles I've had to use throughout, kinda a boiler plate for now
x=0
templist2 = []
templist3 = []
templist4 = []
templist5 = []
bad = {}
#this is my list of "bad actors", list is in the following format
#[saddr as a integer, daddr as a integer, port, date as Julian, time as decimal number]
#or an arbitrary example [1053464536, 1232644361, 2222, 2014260, 15009]
badactor = 'badactor.json'
with open(badactor, 'r') as f1:
badact = json.load(f1)
f1.close()
for i in badact:
print i[3] #troubleshooting to verify my value is being read in
tmp = str(i[3])
print tmp#again just troubleshooting
tl=[i[0],i[4],i[1],i[2]]
bad[tmp]=bad[tmp]+tl
print bad[tmp]
Trying to create the variable is giving me the following error:
Traceback (most recent call last):
File "savetofiles.py", line 39, in <module>
bad[tmp]=bad[tmp]+tl
KeyError: '2014260'
By the time your code is executed, there is no key "2014260" in the "bad" dict.
Your problem is here:
bad[tmp]=bad[tmp]+tl
You're saying "add t1 to something that doesn't exist."
Instead, you seem to want to do:
bad[tmp]=tl
I suggest you initialize bad to be an empty collections.defaultdict instead of just regular built-in dict. i.e.
import collections
...
bad = collections.defaultdict(list)
That way, initial empty list values will be created for you automatically the first time a date key is encountered and the error you're getting from the bad[tmp]=bad[tmp]+tl statement will go away since it will effectively become bad[tmp]=list()+tl — where the list() call just creates and returns an empty list — the first time a particular date is encountered.
It's also not clear whether you really need the tmp = str(i[3]) conversion because values of any non-mutable type are valid dictionary (or defaultdict) keys, not just strings — assuming i[3] isn't a string already. Regardless, subsequent code would be more readable if you named the result something else, like julian_date = i[3] (or julian_date = str(i[3]) if the conversion really is required).

Python: Choose random word from list then remove it

The question is to chooses a random word from a list of words you have defined, and then remove the word from the list. The computer should display a jumble of the word and ask the user to guess what the word is. Once the player has guessed the word, another random word should be selected from the list and the game continues until the list of words is empty.
When I run it, i have an error.
Traceback (most recent call last):
File "F:\Computer Science\Unit 3\3.6\3.6 #5.py", line 21, in <module>
word_jamble (random_word)
File "F:\Computer Science\Unit 3\3.6\3.6 #5.py", line 14, in word_jamble
word = list(word)
TypeError: 'list' object is not callable
This is my program
list = ['mutable', 'substring', 'list', 'array', 'sequence']
from random import shuffle
def word_jamble(word):
word = list(word)
shuffle(word)
print ''.join(word)
from random import choice
random_word = choice(list)
word_jamble (random_word)
user_input = raw_input("What's the word? ")
if user_input == choice(list):
del list[index(choice(list))]
You should change your first variable, list, to something else. It is being confused with the built-in list type, and your list object is of course not callable.
The main problem is the variable's name, list. Its a builtin type constructor's name. When you use say list, it shadows the builtin type's name. Apart from that, you can use pop method, like this, to get the random words out of the list easily
words_list = ['mutable', 'substring', 'list', 'array', 'sequence']
import random
while words_list:
print words_list.pop(random.randrange(len(words_list)))
It means exactly what it says:
TypeError: 'list' object is not callable
It is complaining about
word = list(word)
because at this point,
list = ['mutable', 'substring', 'list', 'array', 'sequence']
has already happened.
Once you make list a name for that particular list, it can no longer be a name for the built-in list class. A name only names one thing at a time.
There are a few basic problems with the code:
list = ['mutable', 'substring', 'list', 'array', 'sequence']
list is the list constructor. You should never name your variables after python keywords.
del list[index(choice(l))]
del is very rarely needed in python. My suggestion is that, if you're a begginner, you should forget about it entirely. The proper way of removing elements from lists is using either list.remove (based on element equality) or list.pop (based on index)
def word_jamble(word):
word = list(word)
shuffle(word)
print ''.join(word)
Here, you're using a function to achieve to distinct tasks: shuffling a word, and printing it. Generally, it's a good practice to make each function perform only a specific task - this leads to more reusable and organized code. Instead of printing the result inside the function, consider returning it, and printing it outside.
from random import shuffle
# some code
from random import choice
It's good practice to keep your imports together, and on the beggining of your program. If you're importing two elements from the same module, you can separate them using a comma:
from random import shuffle, choice
Finally, since you want to repeat the game until there are no words left, you need to use a cycle:
while len(word_list)>0: # can be written simply as "while len(word_list):"
#your code here

Python random.sample not working properly?

I'm a complete nab with python.
But now I need a simple storage containing MyObject-objects for some project.
Each object contains a few StringProperties nothing fancy.
Now I want to get from my list of MyObjects, 10 random objects and store them in some other array.
So I went searching and found random.sample and started implemending it.
def get10RandomMyObjects():
# waarders maken
dict = {}
myObjectsList = []
# Lijst vullen
myObjects = MyObject.all()
randomMyObjects = random.sample(myObjects, 10)
for o in randomMyObjects:
dict_myObject = { }
#some random property setting
myObjectsList.append(dict_myObject)
dict['myObjects'] = myObjectsList
return dict
This is the error I get back:
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/random.py", line 314, in sample
n = len(population)
TypeError: object of type 'Query' has no len()
So obviously something is wrong with the random.sample but my noobness can't decypher what it is.
Anyone care to explain me why I can't obtain those 10 random MyObjects I so desire?
random.sample() works on lists. Obviously, MyObject.all() does not return a list but a Query object. If Query is at least iterable then you can write:
myObjects = list(MyObject.all())
Otherwise, you have to create a list from MyObject.all() manually.
Looks like the Query object is a generator. random.sample likes to know how many items there are in order to create the sample. So the simplest thing to do is put the items to be sampled in a list:
randomMyObjects = random.sample(list(myObjects), 10)
There is nothing wrong with random.sample(). What is happening is that myObjects is not a collection.
Most likely, myObjects is an iterator. You'll have to turn it into a list before using it in random.sample():
randomMyObjects = random.sample(list(myObjects),10)
You may also use:
randomMyObjects = MyObject.all().order_by('?')[:10]
Which is faster because it will let the database do the random ordering and only load the 10 first objects into memory.

strip ' from all members in a list

Ok, so I converted each line in a text file into a member of a list by doing the following: chkseq=[line.strip() for line in open("sequence.txt")] So when I print chkseq I get this: ['3','3'] What I would like is for it to instead look like this: [3,3] I know this is possible, I'm just unsure of how! I need them to be intergers, not strings. So if all else fails, that is my main goal in this: create a list from a .txt file whose members are intergers (which would be all the .txt file contained). Thanks!! -OSFTW
It looks like you want to interpret the strings as integers. Use int to do this:
chkseq = [int(line) for line in open("sequence.txt")]
It can also be written using map instead of a list comprehension:
chkseq = map(int, open("sequence.txt"))
iterate over the elements of your list and print them out with your preferred formatting rather than relying on the default formatting when printing the whole list at once.
Say your array is called input, and you want to store the value in an array called chkseq, your code would be:
chkseq = [int(i) for i in input]
Or, if you wanted to do everything all in one line:
chkseq = [int(i.strip()) for i in open("sequence.txt")]
Passing a string to the int constructor will attempt to turn it into a int.
>>> int('3')
3
>>> int('foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'foo'

Categories