更改名称约定,循环生成变量名

时间:2018-06-28 20:44:44

标签: python string list loops ascii

我正在尝试生成大量的变量,但是某些变量可能包含这些变量的子部分。下面的代码是我目前所在的位置。

import string

Num_Phases = 4          # Number of Phases
Subphases = [2, 3]      # Which Phases have Subphases
Num_Subphases = [2, 2]  # How Many Phases the respective Subphase have

Phases = []
for i in range(1, Num_Phases + 1):
    if i < 10:
        # Start with regular name Convention
        PhaseName = "Phase-0%s" %i
        # Check to see if phase has subphase
        for n in range(1, len(Num_Subphases) + 1): 
            if Subphases[n - 1] == i:
                # If there is a Subphase, Check how many Subphases
                for m in range(1, Num_Subphases[n - 1] + 1):
                    # for each subphase define a phase name
                    PhaseName = ("Phase-0%s" %i) + ('').join(string.ascii_lowercase[m-1])
                # Combine Phases into list
                Phases.append(PhaseName)            
        Phases.append(PhaseName) 

我目前得到以下结果:

['Phase-01', 'Phase-02b', 'Phase-02b', 'Phase-03b', 'Phase-03b', 'Phase-04']

但是我希望它是:

['Phase-01', 'Phase-02a', 'Phase-02b', 'Phase-03a', 'Phase-03b', 'Phase-04']

这将用于非常大的数据集,但我将以此为例。

2 个答案:

答案 0 :(得分:1)

m添加到列表阶段时,它将始终设置为范围的最大值。您要覆盖PhaseName,然后再将其添加到“阶段”列表中。您可以在m循环内移动追加,检查重复项以避免添加重复项。

for m in range(1, Num_Subphases[n - 1] + 1):
            # for each subphase define a phase name
            PhaseName = ("Phase-0%s" %i) + ('').join(string.ascii_lowercase[m-1])
            # Combine Phases into list
            if PhaseName not in Phases:
               Phases.append(PhaseName)  

答案 1 :(得分:0)

不使用太多嵌套fors的另一个可能方法是构建一个数组,该数组指示每个阶段的子阶段数,然后可以在列表组合中使用doble来构建最终结果

phases_arr = [1 for i in range(Num_Phases)]
for isub, numsub in zip(Subphases, Num_Subphases):
    phases_arr[isub-1] = numsub + 1

alphabet = string.ascii_lowercase

phases = ["Phase-%02d%s" % (i+1, alphabet[k-1] if k > 0 else "") for i in range(len(phases)) for k in range(phases[i])]