python - 将两个循环合二为一

标签 python python-3.x

我的代码中有三个不同的循环,但我想知道是否有一种方法可以将其中两个循环组合起来,只循环一次。我的代码如下:

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 返回相同的工作表并添加新的数据帧。

最佳答案

frameshighcs 是一样长的,可以用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/

相关文章:

python - 用\and 分隔的十六进制数据是什么类型的?

python - 如何从 <a> python 解析器获取链接

python - 如何在 Python 中使用 aiohttp 读取流式 api 的行?

Python - 如何从一个数组值乘以另一个数组的所有值创建新的乘积和数组

python - 无法使用 MSVC2015 编译 boost.python 1.65.1

python - 聚合 Pandas 数据框

python - 将带有撇号的单词计为一个单词但返回两个单词(python)

python - python中打印函数的错误?

python - 自定义 Python 扩展 - 导入错误 : undefined symbol

Python 反射 - 我可以使用它来获取方法定义的源代码吗