【问题标题】:Python take the last number of each line in a text file and make it into a listPython获取文本文件中每一行的最后一个数字并将其放入列表中
【发布时间】:2013-01-28 14:37:54
【问题描述】:

我只想要每行的最后一个数字。

with open(home + "/Documents/stocks/" + filePath , newline='') as f:
stockArray = (line.split(',') for line in f.readlines())
    for line in stockArray:
        List = line.pop()
        #print(line.pop())
        #print(', '.join(line))
else:
    print("Finished")

我尝试使用 line.pop() 获取最后一个元素,但它只从一行中获取它?如何从每一行获取它并将其存储在列表中?

【问题讨论】:

    标签: python arrays list text


    【解决方案1】:

    你可能只想要这样的东西:

    last_col = [line.split(',')[-1] for line in f]
    

    对于更复杂的 csv 文件,您可能需要查看标准库中的 csv 模块,因为它可以正确处理字段引用等。

    【讨论】:

    • 这将在每个值中包含换行符。
    【解决方案2】:
    my_list = []
    with open(home + "/Documents/stocks/" + filePath , newline='') as f:
        for line in f:
            my_list.append(line[-1]) # adds the last character to the list
    

    应该可以的。

    如果要从文件中添加列表的最后一个元素:

    my_list = []
    with open(home + "/Documents/stocks/" + filePath , newline='') as f:
        for line in f:
            my_list.append(line.split(',')[-1]) # adds the last character to the list
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-07
      • 2016-02-12
      • 2019-02-07
      • 1970-01-01
      • 1970-01-01
      • 2020-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多