减少循环内的行数
Reduce the number of lines inside the loop
我有这个代码:
while count < len(dist_list):
new.loc[base, "1_dist"], new.loc[base, "1_t-"]= dist_list[0], new.loc[base, "t-"]
new.loc[base, "2_dist"], new.loc[base, "2_t-"]= dist_list[1], new.loc[base, "t-"]
new.loc[base, "3_dist"], new.loc[base, "3_t-"]= dist_list[2], new.loc[base, "t-"]
new.loc[base, "4_dist"], new.loc[base, "4_t-"]= dist_list[3], new.loc[base, "t-"]
new.loc[base, "5_dist"], new.loc[base, "5_t-"]= dist_list[4], new.loc[base, "t-"]
new.loc[base, "6_dist"], new.loc[base, "6_t-"]= dist_list[5], new.loc[base, "t-"]
new.loc[base, "7_dist"], new.loc[base, "7_t-"]= dist_list[6], new.loc[base, "t-"]
new.loc[base, "8_dist"], new.loc[base, "8_t-"]= dist_list[7], new.loc[base, "t-"]
new.loc[base, "9_dist"], new.loc[base, "9_t-"]= dist_list[8], new.loc[base, "t-"]
new.loc[base, "10_dist"], new.loc[base, "10_t-"]= dist_list[9], new.loc[base, "t-"]
count += 1
我需要执行相同的代码,但有 100 个变量(1_dist、2_dist...100_dist)。手动地,我将在循环中有 100 行。但我正在寻找一种方法来减少行数。
有人帮我吗?
您已经在迭代 dist_list
,因此您不妨使用 enumerate
并使用该索引而不是手动维护 count
:
for index, data in enumerate(data_list, 1):
new.loc[base, f"{index}_dist"], new.loc[base, f"{index}_t-"] = data, new.loc[base, "t-"]
while count < len(dist_list):
new.loc[base, f"{count + 1}_dist"], new.loc[base, f"{count + 1}_t-"]= dist_list[count], new.loc[base, "t-"]
count += 1
我不太理解代码,但看到你写了这 10 行,你似乎想在第 2 个字符串中再增加 1 个,然后在第 3 个(可能给列表提供索引时)你想要它与计数相同。
我有这个代码:
while count < len(dist_list):
new.loc[base, "1_dist"], new.loc[base, "1_t-"]= dist_list[0], new.loc[base, "t-"]
new.loc[base, "2_dist"], new.loc[base, "2_t-"]= dist_list[1], new.loc[base, "t-"]
new.loc[base, "3_dist"], new.loc[base, "3_t-"]= dist_list[2], new.loc[base, "t-"]
new.loc[base, "4_dist"], new.loc[base, "4_t-"]= dist_list[3], new.loc[base, "t-"]
new.loc[base, "5_dist"], new.loc[base, "5_t-"]= dist_list[4], new.loc[base, "t-"]
new.loc[base, "6_dist"], new.loc[base, "6_t-"]= dist_list[5], new.loc[base, "t-"]
new.loc[base, "7_dist"], new.loc[base, "7_t-"]= dist_list[6], new.loc[base, "t-"]
new.loc[base, "8_dist"], new.loc[base, "8_t-"]= dist_list[7], new.loc[base, "t-"]
new.loc[base, "9_dist"], new.loc[base, "9_t-"]= dist_list[8], new.loc[base, "t-"]
new.loc[base, "10_dist"], new.loc[base, "10_t-"]= dist_list[9], new.loc[base, "t-"]
count += 1
我需要执行相同的代码,但有 100 个变量(1_dist、2_dist...100_dist)。手动地,我将在循环中有 100 行。但我正在寻找一种方法来减少行数。
有人帮我吗?
您已经在迭代 dist_list
,因此您不妨使用 enumerate
并使用该索引而不是手动维护 count
:
for index, data in enumerate(data_list, 1):
new.loc[base, f"{index}_dist"], new.loc[base, f"{index}_t-"] = data, new.loc[base, "t-"]
while count < len(dist_list):
new.loc[base, f"{count + 1}_dist"], new.loc[base, f"{count + 1}_t-"]= dist_list[count], new.loc[base, "t-"]
count += 1
我不太理解代码,但看到你写了这 10 行,你似乎想在第 2 个字符串中再增加 1 个,然后在第 3 个(可能给列表提供索引时)你想要它与计数相同。