尝试为自己的教学优化我的重复代码。
我试图在字典函数中实现for循环,但是没有成功。是否有更快,更高效的方式编写此代码:
blah = dict({'S1_Cycle1': ['S1/S1_Cycle1', 'S1'],
'S1_Cycle2': ['S1/S1_Cycle2', 'S1'],
'S1_Cycle3': ['S1/S1_Cycle3', 'S1'],
'S1_Cycle4': ['S1/S1_Cycle4', 'S1'],
'S1_Cycle5': ['S1/S1_Cycle5', 'S1'],
'S1_Cycle6': ['S1/S1_Cycle6', 'S1'],
'S1_Cycle7': ['S1/S1_Cycle7', 'S1'],
'S1_Cycle8': ['S1/S1_Cycle8', 'S1'],
'S1_Cycle9': ['S1/S1_Cycle9', 'S1'],
'S1_Cycle10': ['S1/S1_Cycle10', 'S1'],
'S1_Cycle11': ['S1/S1_Cycle11', 'S1'],
'S1_Cycle12': ['S1/S1_Cycle12', 'S1'],
'S1_Cycle13': ['S1/S1_Cycle13', 'S1'],
'S1_Cycle14': ['S1/S1_Cycle14', 'S1'],
'S1_Cycle15': ['S1/S1_Cycle15', 'S1'],
'S1_Cycle16': ['S1/S1_Cycle16', 'S1'],
'S1_Cycle17': ['S1/S1_Cycle17', 'S1'],
'S1_Cycle18': ['S1/S1_Cycle18', 'S1'],
'S1_Cycle19': ['S1/S1_Cycle19', 'S1'],
'S1_Cycle20': ['S1/S1_Cycle20', 'S1'],
'S1_Cycle21': ['S1/S1_Cycle21', 'S1'],
'S1_Cycle22': ['S1/S1_Cycle23', 'S1'],
'S1_Cycle23': ['S1/S1_Cycle23', 'S1'],
'S2_Cycle1': ['S1/S1_Cycle1', 'S2'],
'S2_Cycle2': ['S1/S1_Cycle2', 'S2'],
'S2_Cycle3': ['S1/S1_Cycle3', 'S2'],
'S2_Cycle4': ['S1/S1_Cycle4', 'S2'],
'S2_Cycle5': ['S1/S1_Cycle5', 'S2'],
'S2_Cycle6': ['S1/S1_Cycle6', 'S2'],
'S2_Cycle7': ['S1/S1_Cycle7', 'S2'],
'S2_Cycle8': ['S1/S1_Cycle8', 'S2'],
'S2_Cycle9': ['S1/S1_Cycle9', 'S2'],
'S2_Cycle10': ['S1/S1_Cycle10', 'S2'],
'S2_Cycle11': ['S1/S1_Cycle11', 'S2'],
'S2_Cycle12': ['S1/S1_Cycle12', 'S2'],
'S2_Cycle13': ['S1/S1_Cycle13', 'S2'],
'S2_Cycle14': ['S1/S1_Cycle14', 'S2'],
'S2_Cycle15': ['S1/S1_Cycle15', 'S2'],
'S2_Cycle16': ['S1/S1_Cycle16', 'S2'],
'S2_Cycle17': ['S1/S1_Cycle17', 'S2'],
'S2_Cycle18': ['S1/S1_Cycle18', 'S2'],
'S2_Cycle19': ['S1/S1_Cycle19', 'S2'],
'S2_Cycle20': ['S1/S1_Cycle20', 'S2'],
'S2_Cycle21': ['S1/S1_Cycle21', 'S2'],
'S2_Cycle22': ['S1/S1_Cycle23', 'S2'],
'S2_Cycle23': ['S1/S1_Cycle23', 'S2']
})
答案 0 :(得分:1)
使用字典理解:
{f'S{x}_Cycle{y}': [f'S1/S1_Cycle{y}', f'S{x}'] for x in range(1, 3) for y in range(1, 24)}
输出:
{'S1_Cycle1': ['S1/S1_Cycle1', 'S1'],
'S1_Cycle2': ['S1/S1_Cycle2', 'S1'],
...
...
'S2_Cycle22': ['S1/S1_Cycle23', 'S2'],
'S2_Cycle23': ['S1/S1_Cycle23', 'S2']}