“for”循环如何在2D列表中工作?

2024-09-30 06:21:15 发布

您现在位置:Python中文网/ 问答频道 /正文

所以基本上,我找到了一个可以将CSV文件导入2D列表的代码,但是我无法理解列表中“for”循环是如何工作的。“if”语句中的for循环也一样。

这是我的代码:

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], col[4], eval(col[5])] for col in myFile]

这样我就可以将这种理解有效地、明智地应用到我未来的列表操作中。在


完整代码:

^{pr2}$


^{3}$

Tags: 文件csv代码列表forifmydef
2条回答

上面的代码包含列表理解 您可以通过一个简单的for循环进行突破,并将列数据追加到数组中

def dataRead():
    with open("Inventory_Lists.csv", "r") as my_csv:
      myFile = csv.reader(my_csv, delimiter=",")
      global dataInventoryList
      dataInventoryList =[]

      for col in myFile:
         dataInventoryList.append([col[0], col[1], col[2], col[3], col[4]])
      print(dataInventoryList )

列表理解的简单语法 variablename=[(for循环迭代的数据)(for循环)]

在看代码之前,了解CSV的结构:

  • CSV文件至少有6列
  • 第0到4列有一些随机数据,第5列有数学表达式

简而言之:

   |  0  |  1  |  2  |  3  |  4  |  5  |  - - -
 -+  -+  -+  -+  -+  -+  -+
 0 | d00 | d01 | d02 | d03 | d04 | e05 |  - - -
 1 | d10 | d11 | d12 | d13 | d14 | e15 |  - - -
 2 | d20 | d21 | d22 | d23 | d24 | e25 |  - - -
 . |  .  |  .  |  .  |  .  |  .  |  .  |
 . |  .  |  .  |  .  |  .  |  .  |  .  |
 . |  .  |  .  |  .  |  .  |  .  |  .  |

代码的作用如下:

  1. CSV文件以读取模式打开
  2. 将创建一个全局列表dataInventoryList,以将数据存储在CSV中
  3. for循环遍历CSV文件中的
  4. 当前行中的数据被视为list
  5. eval()语句解决该行中的数学表达式,并将结果追加到前一个list
  6. list附加到dataInventoryList

结果dataInventoryList将是:

^{pr2}$

其中rAB表示通过求解eAB得到的结果


代码中的for循环的更容易理解的等价物是:

dataInventoryList = []

for aRow in myFile:
     rowList = [ aRow[0] , aRow[1] , aRow[2] , aRow[3] , aRow[4] ]
     rowList.append( eval(aRow[5]) )

     dataInventoryList.append( rowList )

希望这有帮助。。!在

相关问题 更多 >

    热门问题