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

求助:解析2D List中的for循环及CSV导入代码逻辑

理解Python中2D列表的循环逻辑(CSV库存操作示例)

我来帮你拆解这段代码里的2D列表循环和逻辑,把每个部分的来龙去脉讲清楚:

1. 用列表推导式生成2D库存列表

先看dataRead()函数里的核心代码:

dataInventoryList = [[col[0], col[1], col[2], col[3], eval(col[4]), eval(col[5])] for col in myFile]

这是列表推导式,本质是一行完成的循环+数据处理:

  • myFile是csv.reader返回的迭代器,它会逐行读取CSV文件,每一行会被拆成一个名为col的列表(比如CSV第一行CS001,Pieces,Hardie Flex,Construction Materials,5,100会被变成["CS001", "Pieces", "Hardie Flex", "Construction Materials", "5", "100"])
  • 遍历每一个col(每一行数据),我们把col的前4个元素直接保留(产品代码、单位、名称、类别),用eval()把第5、6个元素(成本、库存数量)从字符串转成数字
  • 把每个处理后的col重新打包成一个子列表,所有子列表组合起来就变成了dataInventoryList这个2D列表(外层列表是所有库存条目,内层列表是单个条目的各项属性)

2. 嵌套for循环遍历2D列表

代码里打印库存的这段:

for i in range(len(dataInventoryList)):
    for j in range(6):
        print(str(dataInventoryList[i][j]) + "\t", end="")
    print("")

这是典型的索引式嵌套遍历:

  • 外层循环for i in range(len(dataInventoryList)):i是2D列表的行索引,从0到条目总数-1,每次循环对应一个库存条目
  • 内层循环for j in range(6):j是每个子列表的列索引,从0到5(因为每个库存条目有6个属性),每次循环打印当前条目的一个属性,加制表符\t对齐
  • 内层循环结束后执行print(""),实现换行,让每个库存条目占一行

其实这段可以简化成更Pythonic的写法(不用索引,直接遍历元素):

for row in dataInventoryList:
    print("\t".join(map(str, row)))

效果完全一样,可读性更强~

3. 查找并更新库存的循环逻辑

核心是这段处理用户请求的循环:

for i in range(len(dataInventoryList)):
    if search == dataInventoryList[i][0]:
        found = True
        if choice == 1:
            dataInventoryList[i][5] += quantity
            break
        elif choice == 2:
            if dataInventoryList[i][5] == 0:
                print("Requested order is out of stocks!\n")
                break
            elif quantity > dataInventoryList[i][5]:
                print("Requested order is out of range!\n")
                break
            elif quantity <= dataInventoryList[i][5]:
                dataInventoryList[i][5] -= quantity
                break

逻辑拆解:

  • 循环遍历每一个库存条目(通过行索引i定位)
  • 首先判断当前条目的产品代码(dataInventoryList[i][0])是否和用户输入的search匹配:
    • 如果匹配,把found设为True(标记找到目标条目)
    • 根据用户选择的操作(加库存/减库存)执行对应逻辑:
      • 选择1(加库存):直接把当前条目的库存数量(第6个元素,索引5)加上输入的quantity,然后break终止循环(因为已经找到并处理完目标条目,不用继续遍历)
      • 选择2(减库存):先做合法性检查:
        • 如果库存已经是0,打印缺货提示后break
        • 如果请求的数量超过现有库存,打印超出范围提示后break
        • 数量合法的话,就把库存数量减去quantity,然后break
  • 如果循环结束后found还是False,说明遍历完所有条目都没找到匹配的产品代码,就打印找不到的提示

附:完整代码与CSV内容

完整Python代码

import csv  # 注意:原代码里漏了导入csv模块,需要加上!

def dataRead():
    with open("Inventory_List.csv", "r") as my_csv:
        myFile = csv.reader(my_csv, delimiter=",")
        global dataInventoryList
        dataInventoryList = [[col[0], col[1], col[2], col[3], eval(col[4]), eval(col[5])] for col in myFile]
def dataWrite():
    with open("Inventory_List.csv", "w+") as my_csv:
        myFile = csv.writer(my_csv, delimiter=',', lineterminator='\n')
        myFile.writerows(dataInventoryList)
def main():
    while True:
        found = False
        dataRead()
        print("==========================================================================")
        print("Before update;")
        for i in range(len(dataInventoryList)):
            for j in range(6):
                print(str(dataInventoryList[i][j]) + "\t", end="")
            print("")
        search = input("Enter product code: ")
        quantity = int(input("Please enter quantity: "))
        choice = int(input("Add stocks[1] Pull Stacks[2]\nChoice: "))
        for i in range(len(dataInventoryList)):
            if search == dataInventoryList[i][0]:
                found = True
                if choice == 1:
                    dataInventoryList[i][5] += quantity
                    break
                elif choice == 2:
                    if dataInventoryList[i][5] == 0:
                        print("Requested order is out of stocks!\n")
                        break
                    elif quantity > dataInventoryList[i][5]:
                        print("Requested order is out of range!\n")
                        break
                    elif quantity <= dataInventoryList[i][5]:
                        dataInventoryList[i][5] -= quantity
                        break
        if found == False:
            print("Requested order was not found on the database!\n")
        elif found == True:
            dataWrite()
            print("After update;")
            for i in range(len(dataInventoryList)):
                for j in range(6):
                    print(str(dataInventoryList[i][j]) + "\t", end="")
                print("")
main()

Inventory_List.csv内容

CS001,Pieces,Hardie Flex,Construction Materials,5,100
CS002,Pieces,Hammer,Construction Materials,4,100
CS003,Pieces,Mallet,Construction Materials,7,100

内容的提问来源于stack exchange,提问作者Jave Lester Odvina

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:29:33