[Tutor] Naming variables

spir denis.spir at gmail.com
Sun Jan 19 14:23:44 CET 2014


On 01/18/2014 07:20 PM, Pierre Dagenais wrote:
> Hello,
>
> I wish to fill a list called years[] with a hundred lists called
> year1900[], year1901[], year1902[], ..., year1999[]. That is too much
> typing of course. Any way of doing this in a loop? I've tried stuff like
> ("year" + str(1900)) = [0,0] but nothing works.
> Any solution?
>
> Thank you,
>
> PierreD.

I think Danny & Wiktor's solutions are the right ones. Danny's is faster a 
simpler (because of direct array indexing), but does not allow giving the true 
year "names" (actually numbers). Wiktor more correctly matches you expectation 
bt is a bit slower because we're searching individual years in a dict.

Here is an alternative, which should about as slow (since it is also searching 
in a dict), and give true (string) names, at the cost of some complication in 
code. The trick is to make a plain object (unfortunately we need a class in 
python for that: it's a "fantom" class) and then directly set years on it as 
plain attributes. Unfortunately, I don't remember of any nice way to traverse an 
object's attributes: we have to traverse its __dict__ explicitely.

======================================
class Years: pass	# fantom class

years = Years()

# set years as attributes:
start_year = 1900
n_years = 3			# 3 years only as example
for i in range (n_years):
     # use setattr(obj, name, value) :
     name  = "year" + str(start_year + i)
     value = [i]      		# give meaningful value maybe ;-)
     setattr(years, name, value)

# access individual year:
print(years.year1901)

# traverse years:
for name in years.__dict__:
     value = years.__dict__[name]
     # unordered, unfortunately
     print("%s : %s" % (name, value))

""" output (by me: order is undefined):
[1]
year1900 : [0]
year1901 : [1]
year1902 : [2]
"""
======================================

denis


More information about the Tutor mailing list