You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python编程:如何高效将示例代码中的for循环转为while循环

Python for循环转while循环高效实现

最直接高效的转换方式不需要额外引入复杂封装,手动维护遍历索引即可,性能和原生for循环基本无差异:

  • 外层遍历行列表的循环:初始化索引i = 0,循环判断条件为i < len(lines),单次循环逻辑执行完后手动将i自增1
  • 内层遍历单行列项的循环:初始化索引j = 0,循环判断条件为j < len(items),单次循环逻辑执行完后手动将j自增1
  • 原代码中transactions01.append(has_item)末尾多余的**是输入笔误,转换时直接删除即可

转换后可直接运行的代码

import pandas as pd 

transactions01 = [] 

file=open('raw-data1.txt','w')
file.write('HotDogs,Buns\nHotDogs,Buns\nHotDogs,Coke,Chips\nChips,Coke\nChips,Ketchup\nHotDogs,Coke,Chips\n')
file.close()

file=open('raw-data1.txt','r')
lines = file.readlines()  

# 外层for循环替换为while
i = 0
while i < len(lines):
    line = lines[i]
    items = line[:-1].split(',')      
    has_item = {}
    # 内层for循环替换为while
    j = 0
    while j < len(items):
        item = items[j]
        has_item[item] = 1
        j += 1
    transactions01.append(has_item)
    i += 1
        
file.close()

data = pd.DataFrame(transactions01)
data.fillna(0, inplace = True)
data

效率说明

这种索引遍历的实现逻辑和Python for循环遍历列表的底层执行逻辑接近,无额外运算开销,时间复杂度和原代码完全一致,输出结果和原代码无差别,是性能最优的转换方案。

内容的提问来源于stack exchange,提问作者Bryan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 01:21:20