我试图通过循环创建一个对象列表(来自前面定义的类)。结构看起来像:
ticker_symbols = ["AZN", "AAPL", "YHOO"]
stock_list = []
for i in ticker_symbols:
stock = Share(i)
pe = stock.get_price_earnings_ratio()
ps = stock.get_price_sales()
stock_object = Company(pe, ps)
stock_list.append(stock_object)
但是我想通过循环向Company-objects(stock_object)添加一个属性。该属性将是来自另一个列表的值,如(任意数字)[5,10,20],其中第一个属性将转到第一个对象,第二个属性转到第二个对象等。是否可以执行以下操作:< / p>
for i, j in ticker_symbols, list2:
#dostuff
?无法让这种嵌套循环自行运行。感谢任何帮助。
答案 0 :(得分:-1)
尝试:
for i, j in zip(ticker_symbols, list2):
或者
for (k, i) in enumerate(ticker_symbols):
j = list2[k]
等效地:
for index in range(len(ticker_symbols)):
i = ticker_symbols[index]
j = list2[index]
答案 1 :(得分:-1)
我相信你所要做的就是改变for循环。 而不是“for i in ticker_symbols:”你应该循环 “for i in range(len(ticker_symbols))”然后使用索引i对第二个列表做任何你想做的事。
ticker_symbols = ["AZN", "AAPL", "YHOO"]
stock_list = []
for i in range(len(ticker_symbols):
stock = Share(ticker_symbols[i])
pe = stock.get_price_earnings_ratio()
ps = stock.get_price_sales()
# And then you can write
px = whatever list2[i]
stock_object = Company(pe, ps, px)
stock_list.append(stock_object)
有些人说使用索引进行迭代并不是一种好习惯,但如果代码有效,我并不这么认为。