Here is my code:
import random
def randnum():
rando = random.sample(range(1000,9999),1)
strrando = list(str(rando))
return strrando
The purpose is being fulfilled, I am generating a list of 4 randomly generated numbers which are turned to type string. The only problem it generates a list that has a set of brackets as strings in the list itself, so it generates 6 strings instead of the 4. I was wondering if anyone could explain to me why this happens?
Related
I have the following list:
original_list = [('Anger', 'Envy'), ('Anger', 'Exasperation'), ('Joy', 'Zest'), ('Sadness', 'Suffering'), ('Joy', 'Optimism'), ('Surprise', 'Surprise'), ('Love', 'Affection')]
I am trying to create a random list comprising of the 2nd element of the tuples (of the above list) using the random method in such a way that duplicate values appearing as the first element are only considered once.
That is, the final list I am looking at, will be:
random_list = [Exasperation, Suffering, Optimism, Surprise, Affection]
So, in the new list random_list, strings Envy and Zest are eliminated (as they are appearin the the original list twice). And the process has to randomize the result, i.e. with each iteration would produce a different list of Five elements.
May I ask somebody to show me the way how may I do it?
You can use dictionary to filter the duplicates from original_list (shuffled before with random.sample):
import random
original_list = [
("Anger", "Envy"),
("Anger", "Exasperation"),
("Joy", "Zest"),
("Sadness", "Suffering"),
("Joy", "Optimism"),
("Surprise", "Surprise"),
("Love", "Affection"),
]
out = list(dict(random.sample(original_list, len(original_list))).values())
print(out)
Prints (for example):
['Optimism', 'Envy', 'Surprise', 'Suffering', 'Affection']
Well, I was trying to define Labels from another list that contain hours but no sucess.
def loop_label():
for item in Acd_horario:
Acd_horario[item] = Label(framerajada, text=[Acd_horario[item]],
font=font_acd, bg=bg_acd, fg=fg_acd, bd=bd_acd,
relief=relief_acd)
loop_label()
I tried like above, but no sucess. The other list I`m using is from another class, with gets the hour of another list of objects from the class itself:
Acd_lista = [Acd_0715, Acd_0745, Acd_0815, Acd_0845, Acd_0915, Acd_0945,
Acd_1015, Acd_1045, Acd_1115, Acd_1145,
Acd_1215, Acd_1245, Acd_1315, Acd_1345, Acd_1415, Acd_1445,
Acd_1515, Acd_1545, Acd_1615, Acd_1645,
Acd_1715, Acd_1745, Acd_1815, Acd_1845, Acd_1915, Acd_1945,
Acd_2015]
Acd_horario = [i.horario for i in Acd_lista]
Maybe is my logic that isn't right. Anyone has any idea on this?
The error I receive is: TypeError list indices must be integers or slices, not str
I have a list of a list that goes like this:
Main_List: [ ['1.2','3.5'],[ ['5.8','8.3'] ]
I am trying to convert one of the sublists into floats, here is what i did:
Main_List[1] = [float(i) for i in Main_List[1]]
but i keep getting an error "ValueError: could not convert string to float: ."
I have tried several other methods but for some reason it keeps complaining about the dot. The lists i am trying to convert have been extracted from a csv file if that makes a difference, but i did print them and they look fine.
What am i doing wrong?
I was able to figure it out, what i had to do is create another list and set it equal to the first sublist then turn all its elements to floats.
for example
Sublist_1 = []
Sublist_1 = MainList[0]
Sublist_1 = map(float, Sublist_1)
total=0
line=input()
line = line.upper()
names = {}
(tag,text) = parseLine(line) #initialize
while tag !="</PLAY>": #test
if tag =='<SPEAKER>':
if text not in names:
names.update({text})
I seem to get this far and then draw a blank.. This is what I'm trying to figure out. When I run it, I get:
ValueError: dictionary update sequence element #0 has length 8; 2 is required
Make an empty dictionary
Which I did.
(its keys will be the names of speakers and its values will be how many times s/he spoke)
Within the if statement that checks whether a tag is <SPEAKER>
If the speaker is not in the dictionary, add him to the dictionary with a value of 1
I'm pretty sure I did this right.
If he already is in the dictionary, increment his value
I'm not sure.
You are close, the big issue is on this line:
names.update({text})
You are trying to make a dictionary entry from a string using {text}, python is trying to be helpful and convert the iterable inside the curly brackets into a dictionary entry. Except the string is too long, 8 characters instead of two.
To add a new entry do this instead:
names.update({text:1})
This will set the initial value.
Now, it seems like this is homework, but you've put in a bit of effort already, so while I won't answer the question I'll give you some broad pointers.
Next step is checking if a value already exists in the dictionary. Python dictionaries have a get method that will retrieve a value from the dictionary based on the key. For example:
> names = {'romeo',1}
> print names.get('romeo')
1
But will return None if the key doesn't exist:
> names = {'romeo',1}
> print names.get('juliet')
None
But this takes an optional argument, that returns a different default value
> names = {'romeo',2}
> print names.get('juliet',1)
1
Also note that your loop as it stands will never end, as you only set tag once:
(tag,text) = parseLine(line) #initialize
while tag !="</PLAY>": #test
# you need to set tag in here
# and have an escape clause if you run out of file
The rest is left as an exercise for the reader...
I want to write a list of strings to a binary file. Suppose I have a list of strings mylist? Assume the items of the list has a '\t' at the end, except the last one has a '\n' at the end (to help me, recover the data back). Example: ['test\t', 'test1\t', 'test2\t', 'testl\n']
For a numpy ndarray, I found the following script that worked (got it from here numpy to r converter):
binfile = open('myfile.bin','wb')
for i in range(mynpdata.shape[1]):
binfile.write(struct.pack('%id' % mynpdata.shape[0], *mynpdata[:,i]))
binfile.close()
Does binfile.write automatically parses all the data if variable has * in front it (such in the *mynpdata[:,i] example above)? Would this work with a list of integers in the same way (e.g. *myIntList)?
How can I do the same with a list of string?
I tried it on a single string using (which I found somewhere on the net):
oneString = 'test'
oneStringByte = bytes(oneString,'utf-8')
struct.pack('I%ds' % (len(oneString),), len(oneString), oneString)
but I couldn't understand why is the % within 'I%ds' above replaced by (len(oneString),) instead of len(oneString) like the ndarray example AND also why is both len(oneString) and oneString passed?
Can someone help me with writing a list of string (if necessary, assuming it is written to the same binary file where I wrote out the ndarray) ?
There's no need for struct. Simply join the strings and encode them using either a specified or an assumed text encoding in order to turn them into bytes.
''.join(L).encode('utf-8')