import random filename = 'supercu.lmp' file_object = open(filename,'r') lines = file_object.readlines() num_layers = 150 num_atom_a_layer = 20000 idx_gradient = 0.1 num_random = [] for idx_layer in range(1,num_layers+1): num_cu_float = pow(idx_layer/num_layers,idx_gradient)*num_atom_a_layer num_cu = int(num_cu_float) list_random = random.sample(range((idx_layer-1)*num_atom_a_layer,idx_layer*num_atom_a_layer),num_cu) num_random = num_random + list_random num_random.sort() for index in range (len(lines)): strT = lines[index] strL = strT.split() if int(strL[0]) in num_random: strT = strT[:14]+'2'+strT[15:] lines[index] = strT file_object.close strTT = "".join(lines) file_object = open(filename,'w') file_object.write(strTT) file_object.close
时间: 2024-03-10 07:44:48 浏览: 113
LMP.rar_LMP matlab_LMP算法matlab_LMS误码率_lms均衡误码率_lms误码
5星 · 资源好评率100%
这段代码的优化空间还是比较大的,以下是我给出的一些建议:
1. 使用 with 语句打开文件,这样可以确保文件被正确关闭,同时可以减少代码行数。示例:
```
with open(filename, 'r') as file_object:
lines = file_object.readlines()
```
2. 在循环中避免多次计算相同的值,可以将这些值计算出来后存储在变量中。示例:
```
idx_layer_ratio = [idx_layer/num_layers for idx_layer in range(1,num_layers+1)]
num_cu_float_list = [pow(idx, idx_gradient)*num_atom_a_layer for idx in idx_layer_ratio]
```
3. 可以使用列表推导式代替循环,可以使代码更加简洁高效。示例:
```
num_random = [i for idx_layer in range(num_layers)
for i in random.sample(range(idx_layer*num_atom_a_layer, (idx_layer+1)*num_atom_a_layer),
int(num_cu_float_list[idx_layer]))]
num_random.sort()
```
4. 对于字符串的操作可以使用 f-string 或者 format 函数,可以使代码更加简洁易读。示例:
```
strT = f"{strT[:14]}2{strT[15:]}"
```
综上所述,优化后的代码如下所示:
```
import random
filename = 'supercu.lmp'
with open(filename, 'r') as file_object:
lines = file_object.readlines()
num_layers = 150
num_atom_a_layer = 20000
idx_gradient = 0.1
idx_layer_ratio = [idx_layer/num_layers for idx_layer in range(1,num_layers+1)]
num_cu_float_list = [pow(idx, idx_gradient)*num_atom_a_layer for idx in idx_layer_ratio]
num_random = [i for idx_layer in range(num_layers)
for i in random.sample(range(idx_layer*num_atom_a_layer, (idx_layer+1)*num_atom_a_layer),
int(num_cu_float_list[idx_layer]))]
num_random.sort()
for index in range(len(lines)):
strT = lines[index]
strL = strT.split()
if int(strL[0]) in num_random:
strT = f"{strT[:14]}2{strT[15:]}"
lines[index] = strT
with open(filename, 'w') as file_object:
file_object.write("".join(lines))
```
阅读全文