python - 迭代扩展列表/嵌套 for 循环

标签 python for-loop

我正在尝试构建一个脚本来模拟销售股票的策略。其目的是根据一段时间内的股价假设,以更高的价格出售越来越多的股票。定期(每周)创建多个卖单,并保持开放状态,直到它们以高于限价的价格成交(限价是我愿意出售股票的价格)。每个卖单都有不同的限价,因此价格越高,成交的订单就越多,卖出的库存也就越多。

我的方法是使用一个列表来反射(reflect)每周的价格假设,并使用一个列表列表来反射(reflect)每周下的订单。我的目的是每周迭代订单列表并“填写”满足以下条件的订单:

  • 他们将价格限制为低于该周的价格假设
  • 尚未售出

这是脚本的简化版本

orders = [] # initalize an empty list of orders.  Append orders to this list each week.
number_of_weeks = 4 # number of weeks to simulate

weekly_order_template = [[100, 5, "", ""],[150, 10, "", ""]] # these are the orders that will be added each week (2 in this example) and each order includes the number of shares, the limit price, the sale price (if sold), the sale week (if sold).

# create a list to store the weekly price assumptions
weekly_price = [] # init a list to store weekly prices
price = 4.90
price_increment = .05
for weeks in range(0,number_of_weeks):
    price = price + price_increment
    weekly_price.append(price)

# each week, add this week's orders to the orders list and then compare all orders in the list to see which should be sold.  Update the orders list elements to reflect sales.
for week in range(0,number_of_weeks):
    print "****This is WEEK ", week, "****"
    this_weeks_price = weekly_price[week]
    print "This week's price: ", this_weeks_price
    for order in weekly_order_template: # add this week's orders to the orders list
        orders.append(order)
    for order in orders: # iterate over the orders list and update orders that are sold
        if (order[2] == "") and (order[1] < this_weeks_price):
            order[2] = this_weeks_price
            order[3] = week
    print "All orders to date: ", orders

该脚本无法运行。在这些订单存在之前,它是“销售”订单。例如,这是第四周的输出:

****This is WEEK  3 ****
This week's price:  5.1
All orders to date:  [[100, 5, 5.05, 2], [150, 10, '', ''], [100, 5, 5.05, 2], [150, 10,'', ''], [100, 5, 5.05, 2], [150, 10, '', ''], [100, 5, 5.05, 2], [150, 10, '', '']]

为什么第七个元素(第 3 周的第一个订单)以前一周的价格而不是当前价格 5.10 美元“出售”? (注意 - “WEEK 3”指的是第四周,因为我使用第 0 周作为第一周)

最佳答案

Python 使用“引用语义”,换句话说,它永远不会复制某些内容,除非您明确告诉它这样做。

问题出在这一行:

orders.append(order)

它将 order 引用的对象追加到列表中,然后下周再次追加相同的对象。您应该做的是附加它的副本:

orders.append(list(order))

关于python - 迭代扩展列表/嵌套 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11818915/

相关文章:

python - 来自 Python 的 QPX Express API

python - 在 Python 中自动键入转换参数

python - 检查Python字典值是否在另一个字典的值中

javascript - 在嵌套的 for 循环中垂直打印数组。 JavaScript

python - 同时使用 session 上下文管理器和 stream=True

python - 在 python 中打印下标

python - 没有名为 'keras.legacy' 的模块

python - 在数字后签名 "-"

java - 这个Java for 循环终止条件是什么意思?