Python List Bracket Removal

拈花ヽ惹草 提交于 2019-12-11 06:24:14

问题


So I am trying to add a list of ticker symbols from a CSV file into a python list.

The CSV File looks like this:

AAPL
XOM
EMC

When working with the stockList[]. How do I remove the [' '] brackets and quote marks?

My code is below:

stockList = []
csvReader = csv.reader(open('tickers.csv','rb'), quoting=csv.QUOTE_NONE)
for row in csvReader:
    stockList.append(row)

for item in stockList:
    print repr(item)

For example when the code above is ran it outputs:

['AAPL']
['XOM']
['EMC']

回答1:


It looks like CSVReader is returning a list of rows. Modify your code in this way.

for row in csvReader:
    row = "".join(row)
    stockList.append(row)



回答2:


Just use readlines if your data is just a text file with a line-break after each symbol

fh = open('tickers.txt', 'rb')
stockList = [x.rstrip('\n') for x in fh]

That will return you:

['AAPL', 'XOM', 'EMC']

Much easier.



来源:https://stackoverflow.com/questions/9969099/python-list-bracket-removal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!