You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

传递类对象数组仅返回单个属性,如何获取所有列表元素的cond_1属性?

问题根源

你当前代码的核心问题是self.cond_1是单个变量,循环遍历股票列表时每次赋值都会覆盖上一次的结果,所以最终只会保留最后一只股票的判断结果,自然只能输出一个布尔值。

修正后代码

import requests

top_gainer_list = ['AAPL', 'GOOG']

class Gainers:
    def __init__(self, ticker_list):
        self.ticker_list = ticker_list
        # 用字典存储每个股票对应的cond_1结果
        self.cond_1 = {}

    def filter_marketCap(self):
        iexresponse = requests.get(
            "https://cloud.iexapis.com/stable/stock/market/batch?symbols={}&types=quote&token=APIKEY".format(
                ','.join(self.ticker_list)))
        data = iexresponse.json()
        for ticker in self.ticker_list:
            marketCap = int(data[ticker]['quote']['marketCap'])
            if 10000000 <= marketCap <= 200000000:
                self.cond_1[ticker] = True
            else:
                self.cond_1[ticker] = False

top_gainer = Gainers(top_gainer_list)
top_gainer.filter_marketCap()
# 输出所有股票的cond_1结果
print(top_gainer.cond_1)
# 单独查看某只股票的cond_1
print(top_gainer.cond_1['AAPL'])
print(top_gainer.cond_1['GOOG'])

核心修改说明

  • 把self.cond_1改为字典结构,键为股票代码,值为对应的布尔判断结果,避免循环赋值时覆盖旧值
  • 优化类初始化参数命名,将原本的cond_1改为ticker_list,更符合参数实际存储的股票列表含义
  • 接口请求的股票列表从全局变量改为取类内存储的self.ticker_list,降低耦合性
  • 输出时可直接取整个字典查看所有结果,也可通过股票代码单独取对应判断值

内容的提问来源于stack exchange,提问作者bloomsdayforever

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 07:54:03