1

My problem has to do with statistics and the creation of a dynamic number of variables in Python.

I have a data set of values from 0-100.

If the user enters 5 upper limits, 20, 40, 60, 80, 100, the program should sort the values into 5 classes, list1, list2, list3, list4, list5. If the user enters 4 upper limits, 25, 50, 75, 100, the program should sort the values into 4 classes, list1, list2, list3, list4.

Then, I need to find the average for each list, eg, list1Average, list2Average, list3Average, list4Average and store these average values in another list, averagesList.

Finally, I need to subtract the average for each respective class (list1Average, list2Average, list3Average, list4Average) from each value in the dataset. i.e. subtract list1Average from each value in list1, subtract list2Average from each value in list2, etc, and store those derived values in yet another list, classVarianceList.

I've managed to do all of this quite easily, but only when the number of class upper limits is static (I can just do class1.append(i), class2.append(i), etc). But now I'm going insane trying to figure out how to do this when the number of classes can be determined by the user. The main issue is the creation of a dynamic number of variables (lists) to store values and run calculations upon.

I've also read up on Python's dictionaries (because everyone says to use dictionaries to dynamically create variables), and while I get that it ties a key to a value, I just can't for the life of me, figure out how to incorporate this into what I want to do.

Thank you very much for any help!

CompNat
  • 23
  • 1
  • 4
  • 4
    Welcome to SO, please take the [*tour*](http://stackoverflow.com/tour) to see how and which questions should be submitted here. – Nir Alfasi Jul 14 '14 at 04:21

2 Answers2

0

Use lists

my_list = []
my_listAverage = []
my_class = []

then you can have any number of elements

my_list[0]
my_list[1]
my_list[2]

my_list1Average[0]
my_list1Average[1]
my_list1Average[2]

my_class[0]
my_class[1]
my_class[2]

You can use two-dimensional list

my_class[0] = []

my_class[0].append( ... )

my_class[0][0]
furas
  • 134,197
  • 12
  • 106
  • 148
0

Dictionaries are fine if you have indices which are strings, and you don't have to make them up. So if you work by name, or something, a dictionary is easy to use.

If you just use numbers, I'd make a list of lists. You can rapidly configure a list of N elements by doing eg. list_of_lists = N * []. You can the populate each list with the data. Manage a small second list in parallel, with the max values of each of the sub-lists.

Doing this manually can be a little tedious, but if you define a class for what you are doing, you can hide the complexity in the class, and easily reuse it.

jcoppens
  • 5,306
  • 6
  • 27
  • 47