理解每个in.append

  • 本文关键字:in append python
  • 更新时间 :
  • 英文 :


我对编码非常陌生,并试图培养一些技能来帮助投资。

该代码的目的是为所有500家s&P500公司,稍后从中提取历史数据。

import bs4 as bs
import pickle
import requests

def save_sp500_ticker():
resp = requests.get('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies')
soup = bs.BeautifulSoup(resp.text, "lxml")
table = soup.find('table', {'class': 'wikitable sortable'})
tickers = []
for row in table.findAll('tr')[1:]:
tickers = row.findAll('td')[0].text
tickers.append(ticker)
with open('sp500tickers.pickle', 'wb') as f:
pickle.dump(tickers, f)
print(tickers)
return tickers
save_sp500_ticker()

我是然后得到错误:

line 13, in save_sp500_ticker
tickers.append(ticker)
AttributeError: 'str' object has no attribute 'append'

我不明白为什么,因为教我的视频有完全相同的代码,没有错误。

tickers = []
for row in table.findAll('tr')[1:]:
tickers = row.findAll('td')[0].text
tickers.append(ticker)

您已经将tickers对象设置为空列表,然后通过获取text属性将其更改为str(字符串(对象。str对象没有append函数,这就是代码无法运行的原因。

我相信您错误地在ticker的末尾添加了一个s,这是在重新分配tickers对象。您可以通过卸下s来轻松更正它。

tickers = []
for row in table.findAll('tr')[1:]:
ticker = row.findAll('td')[0].text
tickers.append(ticker)

最新更新