【问题标题】:Convert list of ticker symbols into list in Python将股票代码列表转换为 Python 中的列表
【发布时间】:2012-07-16 09:47:46
【问题描述】:

我需要转换一个股票代码列表: 吨 谷歌 KO 政治公众人物 作为文本文件中的示例到 python 列表:['T','GOOG','KO',PEP']。但是,我正在使用的当前代码在每个符号产生后不断添加一个空格: ['T ','GOOG ','KO ',PEP '] 代替。如何获取不带空格的代码?

stocks = open('C:\Model\Stocks\official.txt', 'r').read()
print stocks.split('\n')

【问题讨论】:

  • 显然,标准普尔的 bimbos 决定在 excel 文件的每个符号后放置一个漂亮的小空格。我想我需要弄清楚如何删除它。

标签: python list text-files spaces stocks


【解决方案1】:

我建议使用 strip 函数,它会映射结果:

>>> a = ["A ", "B ", "C "]
>>> a
['A ', 'B ', 'C ']
>>> a = map(lambda x: x.strip(), a)
>>> a
['A', 'B', 'C']

在你的例子中:

a = stocks.split('\n')

【讨论】:

    【解决方案2】:

    给你。

    stocks = open('C:\Model\Stocks\official.txt', 'r').read()
    lstStripped =  [x.strip() for x in stocks.split('\n')]
    print lstStripped 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-07
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      • 2014-10-09
      相关资源
      最近更新 更多