为什么嵌套循环从 0 开始以及如何将其更改为从它离开的地方开始?
why does nested loop start from 0 and how to change it to start from where it had left?
我想生成一个代码,该代码将从两个不同的数据帧中的每一个写入 20 行。因此,我创建了如下所示的内容。一切正常,除了嵌套循环 (u) 每次都从 0 开始。你能帮我如何修复它,从它离开的地方开始吗?
for t, row in results_table1.iterrows():
f.write(" & ".join([str(x) for x in row.values]) + " \\\n")
if t > 0 and t % 20 == 0:
for u, row in results_table2.iterrows():
f.write(" & ".join([str(x) for x in row.values]) + " \\\n")
if u > 0 and u % 20 == 0:
break
你想在两个 table 之间交替吗?然后我将按索引访问内容:
for t in range(20):
f.write(" & ".join([str(x) for x in results_table1.iloc[t].values]) + " \\\n")
f.write(" & ".join([str(x) for x in results_table2.iloc[t].values]) + " \\\n")
编辑:
从 table 1 获取第 0-19 行,然后从 table 2 获取 0-19,然后从 table 获取第 20-39 行等等:
(基于 但确保复制所有行,即使总数不能被 20 整除)
u = 0
for t, row in results_table1.iterrows():
f.write(" & ".join([str(x) for x in row.values]) + " \\\n")
if t > 0 and t % 20 == 0 or t == len(results_table1.index)-1:
for i in range(0,20):
try:
f.write(" & ".join([str(x) for x in results_table2.iloc[u]]) + " \\\n")
u += 1
except KeyError:
break
您可以在循环增量 u 之外初始化 u 并将其用作第二个数据帧的索引。
u = 0
for t, row in results_table1.iterrows():
f.write(" & ".join([str(x) for x in row.values]) + " \\\n")
if t > 0 and t % 20 == 0:
for i in range(0,20):
try:
f.write(" & ".join([str(x) for x in results_table2.iloc[u]]) + " \\\n")
u += 1
except:
pass
f.close()
我想生成一个代码,该代码将从两个不同的数据帧中的每一个写入 20 行。因此,我创建了如下所示的内容。一切正常,除了嵌套循环 (u) 每次都从 0 开始。你能帮我如何修复它,从它离开的地方开始吗?
for t, row in results_table1.iterrows():
f.write(" & ".join([str(x) for x in row.values]) + " \\\n")
if t > 0 and t % 20 == 0:
for u, row in results_table2.iterrows():
f.write(" & ".join([str(x) for x in row.values]) + " \\\n")
if u > 0 and u % 20 == 0:
break
你想在两个 table 之间交替吗?然后我将按索引访问内容:
for t in range(20):
f.write(" & ".join([str(x) for x in results_table1.iloc[t].values]) + " \\\n")
f.write(" & ".join([str(x) for x in results_table2.iloc[t].values]) + " \\\n")
编辑: 从 table 1 获取第 0-19 行,然后从 table 2 获取 0-19,然后从 table 获取第 20-39 行等等:
(基于
u = 0
for t, row in results_table1.iterrows():
f.write(" & ".join([str(x) for x in row.values]) + " \\\n")
if t > 0 and t % 20 == 0 or t == len(results_table1.index)-1:
for i in range(0,20):
try:
f.write(" & ".join([str(x) for x in results_table2.iloc[u]]) + " \\\n")
u += 1
except KeyError:
break
您可以在循环增量 u 之外初始化 u 并将其用作第二个数据帧的索引。
u = 0
for t, row in results_table1.iterrows():
f.write(" & ".join([str(x) for x in row.values]) + " \\\n")
if t > 0 and t % 20 == 0:
for i in range(0,20):
try:
f.write(" & ".join([str(x) for x in results_table2.iloc[u]]) + " \\\n")
u += 1
except:
pass
f.close()