0

I am trying to create an ordered list as follows>

['term1_t1', 'term2_t1', 'term3_t1', 'term4_t1', 'term5_t1', 'term1_t2', 'term2_t2', 'term3_t2', 'term4_t2', 'term5_t2', 'term1_t3', 'term2_t3', 'term3_t3', 'term4_t3', 'term5_t3']

I want the list to vary based on inputs for both the number of terms and the number of time periods "t". A simple list comprehension provides the required output as follows:

terms = 5
periods = 360
lst = ["term{}_t{}".format(j,i) for i in range(1, periods + 1) for j in range(1, terms + 1)]

BUT I saw a suggestion on SO to use lambda and chain, which would look as follows:

f1 = lambda x: "term1_t" + str(x)
f2 = lambda x: "term2_t" + str(x)
f3 = lambda x: "term3_t" + str(x)
f4 = lambda x: "term4_t" + str(x)
f5 = lambda x: "term5_t" + str(x)
investments = list(chain.from_iterable((f1(x), f2(x), f3(x), f4(x), f5(x)) for x in range(1, 361)))

The problem with the above is that I cannot vary the number of terms.

So i was playing around with lambdas within dictionary keys and I don't understand how they work. For example, the following code:

d= {}
for i in range(1, 6):
d["f{}".format(i)] = "term" + str(i) + "_t"
print (d['f1'])

returns:

term1_t

But when I try to incorporate lambda, the following code:

d= {}
for i in range(1, 6):
d["f{}".format(i)] = lambda x: "term" + str(i) + "_t" + str(x)
print (d['f1'](1))

returns:

term5_t1

My question is two-fold:

(1) Why would incorporating the lambda function change value of the portion of the string that it doesn't reference (at least as it seems to me)?

(2) Is there a way to use lambda and chain that would be faster than the comprehension but also allow for changing the number of lambda functions?

Ryan Skene
  • 864
  • 1
  • 12
  • 29

1 Answers1

-1

The problem isn't the lambda itself, it's the i. The str()-function doesn't get evaluated, because the whole lambda doesn't get evaluated until you call it. After the loop, i is equal to 5! To evaluate the str(), try assigning a variable:

d= {}
for i in range(1, 6):
    number = str(i)
    d["f{}".format(i)] = lambda x: "term" + number + "_t" + str(x)
print (d['f1'](1))
GammaSQ
  • 361
  • 1
  • 10