I am trying to feed a vector into a function which checks every element and assigns the corresponding element from the list to the proper if statement.
The output should look like this:
10 11 17 40 370
Somehow I am only receiving the first element
370
and the loop is breaking up.The code looks like the following:
def dosomething(thelist):
period_unit = []
for period in thelist:
period = period.lower()
if period[-1:] == "d":
period_unit = 1
elif period[-1:] == "m":
period_unit = 30
elif period[-1:] == "w":
period_unit = 7
elif period[-1:] == "y":
period_unit = 360
elif period == "dummy":
period_object = 0
return period_object
else:
raise Exception("Something went wrong")
period_object = 10 + period_unit
return period_object
if __name__ == '__main__':
date = ["dummy", "1d", "1W", "1M", "1Y"]
test = dosomething(date )
print(test)
juanpa.arrivillaga
97.6k14 gold badges141 silver badges190 bronze badges
1 Answer 1
You reassign period_unit everytime.
You want to do something like:
def dosomething(thelist):
period_unit = []
for period in thelist:
period = period.lower()
curr_period_unit = None
if period == "dummy":
curr_period_unit = 0
elif period[-1] == "d":
curr_period_unit = 1
elif period[-1] == "m":
curr_period_unit = 30
elif period[-1] == "w":
curr_period_unit = 7
elif period[-1] == "y":
curr_period_unit = 360
else:
raise Exception("Something went wrong")
period_unit.append(10 + curr_period_unit)
return period_unit
And then it works as expected:
>>> date = ["dummy", "1d", "1W", "1M", "1Y"]
>>> dosomething(date)
[10, 11, 17, 40, 370]
>>> ' '.join(str(item) for item in dosomething(date))
'10 11 17 40 370'
answered Nov 16, 2017 at 17:46
Samuel GIFFARD
8421 gold badge8 silver badges23 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
JonDoe
Found the problem. Thanksa lot.
lang-py
period_objectvalues you generate, so each one overwrites the one before it. You're not getting the first value, you're getting the last.