Python 如何向从CSV文件创建的每个命名元组添加ID属性?
我正在使用CSV模块将雅虎的股票报价提取到一个命名元组中Python 如何向从CSV文件创建的每个命名元组添加ID属性?,python,csv,Python,Csv,我正在使用CSV模块将雅虎的股票报价提取到一个命名元组中 YahooQuote = collections.namedtuple( 'YahooQuote', 'date, open, high, low, close, volume, adj_close') def prices(ticker): # make url given ticker csvfile = urllib2.urlopen(url) return map(YahooQuote._mak
YahooQuote = collections.namedtuple(
'YahooQuote', 'date, open, high, low, close, volume, adj_close')
def prices(ticker):
# make url given ticker
csvfile = urllib2.urlopen(url)
return map(YahooQuote._make, csv.reader(csvfile))
雅虎的股票报价csv格式不包括股票代码。如果我调整我的命名元组类以包含一个
ticker
属性,我将如何修改map
表达式,使其将ticker
参数的值添加到每个命名元组实例中?我从基因上无法理解其中包含map()的代码,因此我将把“map(f,I)”转换为“[f(x)代表i中的x]”所以我不必:
return [YahooQuote._make(x) for x in csv.reader(csvfile)]
然后,将ticker添加到csv.reader返回的列表的末尾就很简单了:
YahooQuote = collections.namedtuple(
'YahooQuote', 'date, open, high, low, close, volume, adj_close, ticker')
def prices(ticker):
# make url given ticker
ticker_list = [ticker]
csvfile = urllib2.urlopen(url)
return [YahooQuote._make(x + ticker_list) for x in csv.reader(csvfile)]
很漂亮。我也宁愿使用列表理解。我太傻了,太靠近
命名的tuple
文档了。