Ibe
Ibe

Reputation: 6035

Access complete list for each index of for loop

I have 4 lists such as:

m1_jan = [2.3,3.2]
m1_feb = [3.2,2.3]
m2_jan = [1.2,1.7]
m2_feb = [4.5,6.7] 

and I want to get minimum value of each list and tried following:

mon = ['jan','feb']
for i in xrange(1,3,1):
    for j in mon:
        l = 'm' + str(i) + '_' + j
        print l, min(l)

I get list names right but not getting correct minimum values and instead get following:

m1_jan 1
m1_feb 1
m2_jan 2
m2_feb 2

Any suggestions how to get minimum value of each list?

Upvotes: 0

Views: 31

Answers (2)

Nir Alfasi
Nir Alfasi

Reputation: 53525

If we change:

print l, min(l)

to:

print globals()[l], min(globals()[l])

The output will be as requested:

[2.3, 3.2] 2.3
[3.2, 2.3] 2.3
[1.2, 1.7] 1.2
[4.5, 6.7] 4.5

Explanation:
The variables that you're looking for are stored in the dictionary of globals()

That said, it's a better practice to store these variables in your own dictionary and access them through it, instead of relying on globals()

Upvotes: 3

Sede
Sede

Reputation: 61225

You could just use a dictionary

d = {}
d['m1_jan'] = m1_jan
d['m1_feb'] = m1_feb
d['m2_feb'] = m2_feb
d['m2_jan'] = m2_jan

for mon, min_val in d.items():
    print("{} {}".format(mon, min(min_val)))

Output

m1_feb 2.3
m2_feb 4.5
m2_jan 1.2
m1_jan 2.3

Upvotes: 1

Related Questions