所以基本上,我找到了一个可以将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}$
上面的代码包含列表理解 您可以通过一个简单的for循环进行突破,并将列数据追加到数组中
列表理解的简单语法 variablename=[(for循环迭代的数据)(for循环)]
在看代码之前,了解CSV的结构:
简而言之:
代码的作用如下:
dataInventoryList
,以将数据存储在CSV中for
循环遍历CSV文件中的行list
eval()
语句解决该行中的数学表达式,并将结果追加到前一个list
list
附加到dataInventoryList
结果
^{pr2}$dataInventoryList
将是:其中
rAB
表示通过求解eAB
得到的结果代码中的
for
循环的更容易理解的等价物是:希望这有帮助。。!在
相关问题 更多 >
编程相关推荐