如何使用两个单独的列表推导来填充两个单独的列表?

时间:2017-11-20 06:50:37

标签: python python-3.x

我正在编写代码,使用列表推导(row[0]row[1]分别填充CSV文件(transaction_listrevenue_list)中的两列在Python 3.6.3中。

如果我运行代码,我可以让脚本正确填充revenue_list,但transaction_list将返回一个空列表。

import os, csv
csvpath = os.path.join('budget_data_1.csv')

with open(csvpath) as f:
   readcsv = csv.reader(f, delimiter=',')

   next(readcsv)

   revenue_list = [int(row[1]) for row in readcsv]
   print(revenue_list)

   transaction_list = [row[0] for row in readcsv]
   print(transaction_list)

另一方面,如果我运行代码(注释掉revenue_list = [int(row[1]) for row in readcsv]),我可以让transaction_list返回正确的列表。

import os, csv
csvpath = os.path.join('budget_data_1.csv')

with open(csvpath) as f:
   readcsv = csv.reader(f, delimiter=',')

   next(readcsv)

   #revenue_list = [int(row[1]) for row in readcsv]
   #print(revenue_list)

   transaction_list = [row[0] for row in readcsv]
   print(transaction_list)

问题:当我尝试填充transaction_list transaction_list时,为什么脚本会将revenue_list作为空列表返回写?

0 个答案:

没有答案