【问题标题】:Python create a list from the last column of each row in a csv [duplicate]Python从csv中每一行的最后一列创建一个列表[重复]
【发布时间】:2013-05-26 17:32:58
【问题描述】:

我正在使用 python 3.3。我有一个 csv 文件,但我只想将每行的最后一列用作列表。我可以显示它,但我不能将它存储为列表。 这是我使用的代码。

my_list = []
with open(home + filePath , newline='') as f:
     Array = (line.split(',') for line in f.readlines())
     for row in Array:
          #this prints out the whole csv file
          #this prints out just the last row but I can't use it as a list
          print(', '.join(row))
          print(row[6])

   print(my_list)

那么我将如何获取每行的最后一列(行 [6])并将其放入可以用作整数的列表中?

【问题讨论】:

    标签: python list csv python-3.x


    【解决方案1】:

    使用csv 模块以方便使用,然后是列表理解:

    import csv
    import os
    
    with open(os.path.join(home, filePath), newline='') as f:
        reader = csv.reader(f)
        my_list = [row[-1] for row in reader]
    

    请注意,我使用row[-1] 来挑选每一行的最后一个元素。

    您的代码从未向my_list 添加任何内容; my_list.append(row[6]) 会解决这个问题。

    【讨论】:

    • 谢谢,效果很好。
    猜你喜欢
    • 2016-10-15
    • 2013-07-13
    • 1970-01-01
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-01
    • 1970-01-01
    相关资源
    最近更新 更多