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

二维数组检索时出现'int' object is not subscriptable错误求助

问题修复与功能实现方案

错误根源

你的sell函数遍历了整个portfolio数组,而数组第一个元素是整数类型的现金余额(1000),当循环到这个元素时执行i[0],自然会触发'int' object is not subscriptable错误——整数不支持下标访问。

核心修复与功能实现

1. 重构portfolio结构

为了避免混淆现金和持仓数据,同时支持交易历史记录,调整数组结构如下:

import requests
from datetime import datetime  # 用于生成交易时间戳

TDKEY = "你的API密钥"  # 替换为实际密钥
ticker_input = input("ticker?")
quantity_input = int(input("quantity?"))

# 结构:[现金余额, [持仓列表], [交易历史]]
portfolio = [
    1000,
    [[ticker_input, quantity_input, datetime.now().strftime("%Y-%m-%d %H:%M:%S")]],
    []
]

2. 完善价格获取函数(增加异常处理)

避免API请求失败导致程序崩溃:

def getshareprice(ticker):
    url = f"https://api.twelvedata.com/price?symbol={ticker}&apikey={TDKEY}"
    try:
        r = requests.get(url)
        r.raise_for_status()  # 捕获HTTP错误
        data = r.json()
        price = data.get('price')
        if not price:
            raise ValueError("API未返回有效价格")
        return float(price)
    except Exception as e:
        print(f"获取价格失败: {str(e)}")
        return None

3. 修复sell函数(解决下标错误+持仓验证)

只遍历持仓子数组,同时验证卖出数量不超过持仓量:

def sell(ticker, quantity):
    price = getshareprice(ticker)
    if not price:
        return
    
    # 仅遍历持仓列表(portfolio[1]),避开现金元素
    for holding in portfolio[1]:
        if holding[0] == ticker:
            # 验证卖出数量
            if quantity > holding[1]:
                print(f"持仓不足,当前持有 {holding[1]} 股 {ticker}")
                return
            
            # 更新持仓与现金
            holding[1] -= quantity
            sell_total = price * quantity
            portfolio[0] += sell_total
            
            # 记录交易历史
            portfolio[2].append({
                "type": "sell",
                "ticker": ticker,
                "quantity": quantity,
                "price": price,
                "total": sell_total,
                "date": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            })
            
            # 持仓清零时移除条目
            if holding[1] == 0:
                portfolio[1].remove(holding)
            
            print(f"成功卖出 {quantity} 股 {ticker},获得 {sell_total:.2f},剩余现金 {portfolio[0]:.2f}")
            return
    
    # 未找到对应持仓
    print(f"未持有 {ticker} 股票")

4. 完善buy函数(加入交易历史)

def buy(ticker, quantity):
    price = getshareprice(ticker)
    if not price:
        return
    
    allocated_funds = price * quantity
    if allocated_funds <= portfolio[0]:
        portfolio[0] -= allocated_funds
        
        # 检查是否已有该持仓,有则追加,无则新增
        existing_holding = next((item for item in portfolio[1] if item[0] == ticker), None)
        if existing_holding:
            existing_holding[1] += quantity
        else:
            portfolio[1].append([ticker, quantity, datetime.now().strftime("%Y-%m-%d %H:%M:%S")])
        
        # 记录交易历史
        portfolio[2].append({
            "type": "buy",
            "ticker": ticker,
            "quantity": quantity,
            "price": price,
            "total": allocated_funds,
            "date": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        })
        
        print(f"成功买入 {quantity} 股 {ticker},花费 {allocated_funds:.2f},剩余现金 {portfolio[0]:.2f}")
    else:
        purchasable = int(portfolio[0] // price)
        print(f"资金不足,最多可购买 {purchasable} 股 {ticker}")

5. 交易历史查询功能

def show_transaction_history():
    if not portfolio[2]:
        print("暂无交易记录")
        return
    
    print("\n=== 交易历史 ===")
    for idx, trade in enumerate(portfolio[2], 1):
        print(f"{idx}. {trade['type'].upper()} | {trade['ticker']} | {trade['quantity']}股 | 单价 {trade['price']:.2f} | 总额 {trade['total']:.2f} | {trade['date']}")

测试示例

# 测试买入
buy("AAPL", 2)
# 测试卖出
sell("AAPL", 1)
# 查看交易历史
show_transaction_history()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 05:22:49