0

I have a data set of lists of varying length containing integers in range 0-4 like this:

a = [0, 1, 1, 2, 4, 3, 2]
b = [1, 3, 2, 3, 2]
c = [2, 4, 0, 4, 1, 3, 1, 4]
d = ...

for which I determine frequency of elements using a simple function:

def getFreq(group):
    freq = [0] * 5
    for item in group:
        for i in range(5):
            if (item == i):
                freq[i] += 1
    return freq

that I run for all lists using a for loop like this:

all_groups = [a, b, c]

for group in all_groups:
    getFreq(group)

How do I store the resulting lists automatically so that I can do further operations/comparisons later? Based on comments it appears it is best to use a dictionary. How do I cycle through dictionary keys in the for loop so that the results of each instance of the function are saved to a different key?

  • 3
    Sure you can use a dict, a dict value can be a list (or any other Python object, or nested object, e.g. "list of tuples of defaultdicts", or whatever). In your case, you can have a dict `freq` with keys 'a','b',... – smci Oct 27 '20 at 22:46
  • By the way, you're not assigning the result returned from `getFreq(group)` to any variable. – smci Oct 27 '20 at 22:47
  • Do you want to retitle/restate the question? This is a duplicate of existing questions. – smci Oct 27 '20 at 22:50
  • Why do you have to necessarily have separately named variables for this? What's wrong with using a dictionary? – General Poxter Oct 27 '20 at 22:51

3 Answers3

2

You can unpack a list comprehension like this to get the results in different variables:

freq_a, freq_b, freq_c = [getFreq(group) for group in all_groups]
jignatius
  • 6,304
  • 2
  • 15
  • 30
1

You can use:

freq_a, freq_b, freq_c = [getFreq(x) for x in [a, b, c]]

Also, given that the items in a, b, and c are all integers, you can optimize your function a bit:

def getFreq(group):
    freq = [0] * 5
    for item in group:
        while item > (len(freq) - 1):
            freq.append(0)
        
        freq[item] += 1
    
    return freq

This immediately allows for more dynamic values in your groups :-)

ErikRtvl
  • 326
  • 1
  • 7
0

you could store them in a list since you should know the order (index of the variable in all_groups corresponds)

all_freqs = [getFreq(group) for group in all_groups]
#[[1, 2, 2, 1, 1], [0, 1, 2, 2, 0], [1, 2, 1, 1, 3]]
Ironkey
  • 2,568
  • 1
  • 8
  • 30