简体   繁体   English

如何使用python类中的列表创建字典?

[英]how to create a dictionary using lists in a python class?

I am trying to create a portfolio class. 我正在尝试创建一个投资组合类。 I want to zip my two lists into a dictionary but when ai try to print it out, it is empty(even though my lists are not). 我想将我的两个列表压缩到字典中,但是当ai尝试将其打印出来时,它是空的(即使我的列表不是)。 Am i missing something?? 我错过了什么吗?

import numpy as np

class Portfolio(object):
    """description of class"""

    array_of_stock_prices=[]
    array_of_stock_names=[]
    #create a dictionary of stocks
    stocks=dict(zip(array_of_stock_names,array_of_stock_prices))


    def __init__(self):
        print()    

    def AddStock(self,stock_ticker,stock_price):
        self.array_of_stock_names.append(stock_ticker)
        self.array_of_stock_prices.append(stock_price)


    def printObject(self):
        for key,value in self.stocks.items():
            print(key,value)


port1=Portfolio()
port1.AddStock('AApl',100)
port1.printObject()

You create the dictionary only once, with empty lists. 您只能使用空列表创建一次字典。 If you want to keep it up to date, put that line of code after every extension of the lists (in the end of AddStock ), and keep this dictionary as an attribute of self , like 如果您想使其保持最新,请将该行代码放在列表的每个扩展名之后(在AddStock的末尾),并将此字典保留为self的属性,例如

self.stocks = dict(zip(self.array_of_stock_names, self.array_of_stock_prices))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM