How to refer to multiple arrays with similar names?

Viewed 115

I have a piece of code that looks a bit like this:

     for peak in R_max_peaks, R_min_peaks:
        rounded = '%s' % float('%.1g' % peak)
        if rounded not in result_R:
            attractors_R[i].append(rounded)

But I also have other arrays that only change 'R' for other letters, such as

     for peak in N_max_peaks, N_min_peaks:
        rounded = '%s' % float('%.1g' % peak)
        if rounded not in result_N:
            attractors_N[i].append(rounded)

Is there any pythonic way I could avoid writing this same piece of code multiple times, changing only the capital letter, for a set of capital letters? Something like ('R', 'N', 'H', 'P'), for example?

2 Answers

you could put them all in a dictionary

max_peaks = {'R':[...], 'N':[...]}
min_peaks = {'R':[...], 'N':[...]}
result = {'R':[...], 'N':[...]}
attractors = {'R':{...}, 'N':{...}}
i = 0# I don't know what the variable i comes from

def func(max_peaks, min_peaks, result):
    # t = type, 'R', 'N',...
    attractor = []
    for peak in max_peaks, min_peaks:
        rounded = '%s' % float('%.1g' % peak)
        if rounded not in result:
            attractor.append(rounded)
    return attractor

for t in max_peaks.keys():
    attractors[t][i] = func(max_peaks[t], min_peaks[t], result[t])

Try adding all the capital letters to a list. Eg: letters = ['R', 'N', 'H', 'P']

Iterate over each capital letter in the list:
    Run the code that was to be repeated.
Related