【问题标题】:How to refer to multiple arrays with similar names?如何引用具有相似名称的多个数组?
【发布时间】:2020-10-22 22:51:57
【问题描述】:

我有一段代码看起来有点像这样:

     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)

但我也有其他数组只更改其他字母的“R”,例如

     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)

有没有什么pythonic方法可以避免多次编写同一段代码,只更改大写字母,一组大写字母?例如('R'、'N'、'H'、'P')之类的东西?

【问题讨论】:

  • 您可能应该以不同的方式组织您的代码。实现一个接受参数max_peaksmin_peaks 等的函数,然后用不同的值调用它。
  • 您也可以考虑将 max_peaks、min_peaks 等存储在一个类中,因为它们似乎是相关的。

标签: python


【解决方案1】:

你可以把它们都放在字典里

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])

【讨论】:

    【解决方案2】:

    尝试将所有大写字母添加到列表中。 例如:letters = ['R', 'N', 'H', 'P']

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-28
      • 2014-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      相关资源
      最近更新 更多