我的代码中有三个不同的循环,但我想知道是否有一种方法可以将其中两个循环组合起来,只循环一次。我的代码如下:
for x in groups:
A bunch of code that produces the following...
frames[x]
highcs[x]
然后我循环执行下面的两个循环。这些是我正在尝试组合的。
for x, frame in frames.items():
more unrelated code
for x, highc in highcs.items():
最后两个循环实际上只是使用 xlsxwriter 创建 excel 工作簿。第一个循环创建工作簿并将来自 frames[x] 的数据帧输入到工作表中。然后 highc 返回相同的工作表并添加新的数据帧。
最佳答案
frames
和highcs
是一样长的,可以用zip()一次性迭代:
for (f,frame), (h, highc) in zip(frames.items(), highcs.items()):
# do your work here
zip()
This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.The returned list is truncated in length to the length of the shortest argument sequence.
关于python - 将两个循环合二为一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36749397/