python-3.x - How to speed up or replace the nested loops
问题描述
Can I ask is there any other way to speed up or replace the nested loops?
I am trying to capture the data from excel file there are 66 rows of data with each "A, B, C, D" lines
import xlwings as xw
import glob as glob
import itertools
letters = ['A','B','C','D']
for i in range(66):
for j in range(len(letters)):
sht1 = wb.sheets['Pallet Configurations']
val = (sht1.range(letters[j] + str(i+2)).options(numbers=str).value)
valueList[j].append(val)
I try to use itertools.product but it's not working.
for i, j in itertools.product(66,len(letters)):
sht1 = wb.sheets['Pallet Configurations']
val = (sht1.range(letters[j] + str(i+2)).options(numbers=str).value)
valueList[j].append(val)
解决方案
I'm not sure exactly which library you are using to manipulate what looks like workbook sheets, however you shouldn't need to set sht1
every time in your inner for loop. Your code could be written as:
sht1 = wb.sheets['Pallet Configurations']
letters = ['A','B','C','D']
for i in range(66):
for j in range(len(letters)):
val = (sht1.range(letters[j] + str(i+2)).options(numbers=str).value)
valueList[j].append(val)
This should save you needing to call .sheets
on wb
each time. Additionally, it looks like whichever library you are using can read in a range of of cells at a time. It would probably be less expensive to read the whole row once, before you enter your inner loop. You could then take advantage of Python's List.extend()
method to add the entire list of cells to valueList
.
Sample code might look like:
sht1 = wb.sheets['Pallet Configurations']
letters = ['A','B','C','D']
for i in range(66):
for j in range(len(letters)):
letter = str(letters[j])
vals = (sht1.range("{0}{1}{0}{2}".format(letter, "2:", "66").options(numbers=str).value)
valueList[j].extend(val)
This is still not perfect though and there are probably other ways you could speed up your loops. You need to think about minimising what is done in your loop.
推荐阅读
- rest - 您是否必须指定所有路由以符合rest api?
- column-count - 为什么我的列数不能在 chrome 和 safari 中正常工作?
- unity3d - Unity 2D 自动滚动射击游戏
- php - 没有语法错误仍然没有写入php文件
- javascript - 在 VUE 中向另一个 URL 或选项卡发送/接收消息
- google-sheets - 查询公式不适用于错误 AVG_SUM_ONLY_NUMERIC
- r - 根据对应元素输出嵌套列表的名称
- python - 类型错误:模型()得到了一个意外的关键字参数“batch_size”
- ios - 如何通过电子邮件链接/magic-url 登录以打开 pwa 而不是浏览器来验证 iOS 设备中的用户?
- android-constraintlayout - MATCH_CONSTRAINTS 在动态生成的加权链中不起作用