I hope that you're doing well.
I'm kinda blocked on one part of my project. This a finance oriented project.
Basically, what I want is to loop through a dictionary of financial characteristics such as this:
indices={'Revenues':revenue,'Cost Of Revenues':COGS,'Selling General & Admin Expenses':SGA,
'R&D Expenses':RD,'Operating Income':OperatingIncome}
During my for loop, I wish to have just one line rather than doing this:
if count==1:
prediction_revenue=finalpred
elif count==2:
prediction_COGS=finalpred
elif count==3:
prediction_SGA=finalpred
elif count==4:
prediction_RDA=finalpred
else:
prediction_operatingincome=finalpred[[key,'Date']]
Do you know how I could do that? That would greatly help me.
It's never a good idea to generate variables. Proper pythonic way of doing this is to use a dictionary:
prediction = {}
if count==1:
prediction['revenue'] = finalpred
elif count==2:
prediction['COGS'] = finalpred
elif count==3:
prediction['SGA'] = finalpred
elif count==4:
prediction['RDA'] = finalpred
else:
prediction['operatingincome'] = finalpred[[key,'Date']]
Not sure if this is what you are looking for, but you can access dictionary values through it's keys.
prediction['revenue'] = finalpred
prediction['COGS'] = finalpred
prediction['SGA'] = finalpred
prediction['RDA'] = finalpred
prediction['operatingincome'] = finalpred[[key,'Date']]
If your intention is to just assign finalpred to any key in your dictionary that's easy:
for prediction_name, prediction_value in indices:
prediction_value = finalpred
You can iterate any dictionary like in the example above.
Related
beatles = []
print(beatles)
beatles.append("John Lennon")
beatles.append("Paul McCartney")
beatles.append("George Harrison")
print(beatles)'
for i in range(len(beatles):
beatles.append("Stu Sutcliffe")
beatles.append("Pete Best")
Need help with the for loop using append()
I'm Honestly not too sure what your asking for but to my understanding your looking for a way to add to a list using input then try this out for size.
You can replace list() with [] if you desire
beatles = list()
while True:
inp = input("Add Name to list ")
if inp == 'done' : break
beatles.append(inp)
beatles.append("John Lennon")
beatles.append("Paul McCartney")
beatles.append("George Harrison")
print(beatles)
I am trying to remove all data = to the key given inside of a linked list.
v = 1
while v == 1:
p,c,i = self._linear_search(key)
if i == -1:
v += 1
if c is not None:
p._next = c._next
It removes the first value in the list but fails to continue and remove the following data = to the key in the linked list.
I am curious as to how this does not work, I am calling the helper method to find the key. Once a node is removed, why does it not call to the next node in the list to remove that one???
Thank you
Figured it out. Switching the
if i == -1:
v+=1
TO
elif i == -1:
v+=1
AT THE END OF THE LOOP:
However, Is someone able to use a computational approach to this, as to how the computer read my code.
i am making a simple substitution cipher in python. i want this program to go through the characters in a string, then add their number values to an array, but it give me this error:
Traceback (most recent call last):
File "D:\py programs\simple cypher.py", line 39, in <module>
x[i]=18
IndexError: list assignment index out of range
here is my code:
pt=raw_input('string to encrypt ')
x=[]
for i in range (0, len(pt)):
if pt[i]=='a':
x[i]=1
elif pt[i]=='b':
x[i]=2
elif pt[i]=='c':
x[i]=3
elif pt[i]=='d':
x[i]=4
elif pt[i]=='e':
x[i]=5
elif pt[i]=='f':
x[i]=6
elif pt[i]=='g':
x[i]=7
elif pt[i]=='h':
x[i]=8
elif pt[i]=='i':
x[i]=9
elif pt[i]=='j':
x[i]=10
elif pt[i]=='k':
x[i]=11
elif pt[i]=='l':
x[i]=12
elif pt[i]=='m':
x[i]=13
elif pt[i]=='n':
x[i]=14
elif pt[i]=='o':
x[i]=15
elif pt[i]=='p':
x[i]=16
elif pt[i]=='q':
x[i]=17
elif pt[i]=='r':
x[i]=18
elif pt[i]=='s':
x[i]=19
elif pt[i]=='t':
x[i]=20
elif pt[i]=='u':
x[i]=21
elif pt[i]=='v':
x[i]=22
elif pt[i]=='w':
x[i]=23
elif pt[i]=='x':
x[i]=24
elif pt[i]=='y':
x[i]=25
elif pt[i]=='z':
x[i]=26
elif pt[i]==' ':
x[i]='_'
print x
can anybody help?
In Python you cannot assign to an index greater than the length of the list, so each of your x[i] = ... lines would cause this IndexError.
Instead you would need to change all of these to x.append(...), which will add a new element to the end of the list.
Really though, your entire code could be refactored so that it is much shorter:
import string
pt = raw_input('string to encrypt ')
trans = {c: i for i, c in enumerate(string.lowercase, 1)}
trans[' '] = '_'
x = [trans[c] for c in pt if c in trans]
print x
What you currently are trying to do is better written like this:
pt = raw_input('string to encrypt ')
x = [ord(i)-96 for i in pt]
If this really is what you need depends on what you intended to do next, but hopefully that takes you a bit further.
http://docs.python.org/2/library/string.html
string.maketrans(from, to)
Return a translation table suitable for passing to translate(), that will map each character in from into the character at the same position in to; from and to must have the same length.
Assign the translated to a separate list possibly? If this is what your looking for...
input_alphabet="abcde"
output_alphabet="12345"
trantab = maketrans(input_alphabet,output_alphabet)
text="translate abcdefg"
print text.translate(trantab)
Your list x is empty, so there is no x[i] to assign to: just as the error message says. Instead, use x.append(...). Or define x as x = [None] * len(pt) so that there are slots to fill.
Of course, there are much, much simpler and shorter ways of doing what you're trying to do. Try a dictionary, or the translate() method of strings.
The list is empty what you need is:
x.insert(i,1)
Which inserts the value 1 in index i
I am having trouble understanding lists:
mList = []
def func1(mList):
mList.append("1")
return
func1()
print mList
As I understand it because a list is mutable, if I edit it in a function, the main list will also be edited. In a program I am working on this is happening with one list which I am using as a "save file", however, a second list which I am using as a "value_blacklist" is not being saved after it is edited/added to.
I included the problem part of the actual code I am having issues with if it's of any help.
def func04(feedback, test_list, value_blacklist, upper_limit=6):
if value_blacklist == []:
value_blacklist = blacklist_gen(length)
import random
new_list = []
for index in list(range(0, len(feedback))):
if feedback[index] == 0: #This value is correct, leave it
new_list.append(test_list[index])
elif feedback[index] == 2:
value_blacklist = full_blacklist(test_list[index], value_blacklist)
new_list.append(0)
elif feedback[index] == 1:
value_blacklist[index].append(test_list[index])
new_list.append(0)
for index in list(range(0, len(feedback))):
if new_list[index] == 0:
new_list[index] = pick_new(index, value_blacklist, upper_limit)
return new_list
next_guess = lambda: func04(feedback(), save_game[-1], value_blacklist, save_game[0])
Thanks for any help, I'm really confused by this.
Whereever you are saying
value_blacklist = ...
You are rebinding value_blacklist to a new (list) object. If you instead say
value_blacklist[:] = ...
You will replace the contents of the list without rebinding it.
Ask lots of questions until you really really understand this. It's very important to "get" it.
When you use = operator in a function, you are not modifying the existing object. Right hand side of the expression creates a new list and returns a reference to it and that reference is assigned to value_blacklist.
value_blacklist = blacklist_gen(length)
...
value_blacklist = full_blacklist(test_list[index], value_blacklist)
These are the places where you create new local lists and referring them with value_blacklist. That's why value_blacklist doesn't reflect the changes. You can confirm this by printing the id of value_blacklist after the assignment statements and at the beginning of the function.
I must be missing something here when I try to populate a tuple in a for loop.
...more code above...
colItems = objSWbemServices.ExecQuery(queryString)
#print type(colItems)
Is the above line needed?
# print the results
for item in colItems:
logTuple = (item.SourceName, item.Type, item.TimeGenerated, item.Message)
logTuple.sort(sortByTime)
return logTuple
Would the above code enter those fields into a tuple?
Below is the code to sort, I haven't been able to test it yet though.
def sortByTime(t1, t2):
if t1[2] < t2[2]:
return -1
elif t1[2] > t2[2]:
return 1
else:
return 0
Thanks for the help.
I'm not familiar with ExecQuery or the structures you're using, but I do know that in your for loop you're rewriting logTuple each time the body of the loop is executed. This should do the trick:
logTuples = []
for item in colItems:
logTuples.append( (item.SourceName, item.Type, item.TimeGenerated, item.Message) )
logTuples.sort(key=operator.itemgetter(2)) #credit: Thomas Jung
return logTuples
What you probably meant was to add the tuple to the list (and not to set logTuple to the last created tuple in the for loop):
for item in colItems:
log = (item.SourceName, item.Type, item.TimeGenerated, item.Message)
logTuple.append(log)
The sorting can be done with:
logTuples.sort(key=operator.itemgetter(2))