Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 使用对象动态构建列表_Python 3.x - Fatal编程技术网

Python 3.x 使用对象动态构建列表

Python 3.x 使用对象动态构建列表,python-3.x,Python 3.x,我正在创建一个SP 500组件列表,以将其保存在pickle中 我从代码中的链接中获取项目,然后获取我想要的信息,并为每个项目构建一个对象 问题是-> 然后,我想将每个对象保存到一个列表中,以便将来迭代 该列表仅存储循环的最后一个对象,而不是存储显示的每个对象 这应该是相当容易做到这一点,但我似乎无法找到为什么会发生这种情况的答案 def save_sp500_tickers(): resp = requests.get( 'https://en.wikipedia.or

我正在创建一个SP 500组件列表,以将其保存在pickle中

我从代码中的链接中获取项目,然后获取我想要的信息,并为每个项目构建一个对象

问题是-> 然后,我想将每个对象保存到一个列表中,以便将来迭代

该列表仅存储循环的最后一个对象,而不是存储显示的每个对象

这应该是相当容易做到这一点,但我似乎无法找到为什么会发生这种情况的答案

def save_sp500_tickers():
    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'})
    components = []
    data = {}
    for row in table.findAll('tr')[1:]:

        ticker = row.findAll('td')[0].text.replace('\n', '') # AAPL
        name = row.findAll('td')[1].text.replace('\n', '') # Apple Inc
        sector = row.findAll('td')[3].text.replace('\n', '') # Information Technology
        mapping = str.maketrans(".", "-")

        ticker = ticker.translate(mapping)
        name = name.translate(mapping)
        sector = sector.translate(mapping)

        data['ticker']=ticker
        data['name']=name
        data['sector']=sector

        print(data) # {'ticker': 'AAPL', 'name': 'Apple Inc-', 'sector': 'Information Technology'}
        components.append(data) # I add each component to the list


    with open("SP500components.pickle", "wb") as f:
        pickle.dump(components, f)

    print(components) # this gives me the list with only the last item repeated 

    return components

save_sp500_tickers()
目标是创建一个如下所示的列表:

[{'ticker': 'AAPL', 'name': 'Apple Inc-', 'sector': 'Information Technology'},
{'ticker': 'ETN', 'name': 'Eaton Corporation', 'sector': 'Industrials'},
{'ticker': 'EBAY', 'name': 'eBay Inc-', 'sector': 'Consumer Discretionary'},
{'ticker': 'ECL', 'name': 'Ecolab Inc-', 'sector': 'Materials'},
{'ticker': 'EIX', 'name': "Edison Int'l", 'sector': 'Utilities'},
...,
...]
相反,我得到的列表只多次显示最后一个对象,如下所示:

[{'ticker': 'ZTS', 'name': 'Zoetis', 'sector': 'Health Care'},
{'ticker': 'ZTS', 'name': 'Zoetis', 'sector': 'Health Care'},
{'ticker': 'ZTS', 'name': 'Zoetis', 'sector': 'Health Care'},
{'ticker': 'ZTS', 'name': 'Zoetis', 'sector': 'Health Care'},
...,
...]
这完全取决于您的数据对象。在for循环外初始化它。因为它是一个字典,所以在python中是可变的,当您将它附加到列表中时,您只需在循环的每个迭代中添加对该数据的引用,而不是一个新字典。所以在最后,参考文献只是指向了最新版本的dict,因此它多次出现在同一个dict上——它是同一个dict

可能有助于了解正在发生的事情

尝试将dict的初始化移动到for循环中:

def save_sp500_tickers():
    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'})
    components = []
    for row in table.findAll('tr')[1:]:
        ticker = row.findAll('td')[0].text.replace('\n', '') # AAPL
        name = row.findAll('td')[1].text.replace('\n', '') # Apple Inc
        sector = row.findAll('td')[3].text.replace('\n', '') # Information Technology
        mapping = str.maketrans(".", "-")

        ticker = ticker.translate(mapping)
        name = name.translate(mapping)
        sector = sector.translate(mapping)

        data = dict(ticker=ticker, name=name, sector=sector)

        print(data) # {'ticker': 'AAPL', 'name': 'Apple Inc-', 'sector': 'Information Technology'}
        components.append(data) # I add each component to the list


    with open("SP500components.pickle", "wb") as f:
        pickle.dump(components, f)

    print(components) # this gives me the list with only the last item repeated 

    return components