【问题标题】:Getting wrong answer from data length calculation从数据长度计算中得到错误的答案
【发布时间】:2021-08-12 02:39:17
【问题描述】:

我有一个来自我定义的函数的 41 个数据的列表,但我只想访问其中的前 40 个。所以,我正在寻找的索引位置是从 0 - 39

forecast_price(10)[:len(forecast_price(10)) - 1] 

我还把它变成了一个变量,以便在我的代码中进一步参考:

forecast_w10 = forecast_price(10)[:len(forecast_price(10)) - 1] 

但是,当我尝试打印变量中数据的长度时,我仍然得到 41。我觉得错误就在我的眼皮底下,但似乎无法弄清楚。我做错了什么?

In[46]: print(len(forecast_w10))
Out[46]: 41

【问题讨论】:

  • 只要forecast_price(10)[:-2]
  • 重新检查一次forecast_price(10)的长度。
  • @enzo 尝试这样做,但我仍然得到 41 作为输出:(
  • @Ank也这样做了,长度是41

标签: python variable-length


【解决方案1】:

为了重现性,我们假设 forecast_price 是一个返回 41 个元素列表的函数,从给定的初始值 x 开始:

def forecast_price(x):
    return [i + x for i in range(41)]

print(forecast_price(1))          # [1, 2, 3, ..., 39, 40, 41]
print(len(forecast_price(1)))     # 41

print(forecast_price(10))         # [10, 11, 12, ..., 48, 49, 50]
print(len(forecast_price(10)))    # 41

由于您只想访问前 40 个值,请使用切片运算符:

forecast_w10 = forecast_price(10)[:40] 
print(forecast_w10)               # [10, 11, 12, ..., 47, 48, 49]
print(len(forecast_w10))          # 40

【讨论】:

  • 谢谢!我好像把自己的代码弄复杂了哈哈哈
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-09
  • 2011-06-26
  • 2016-10-23
  • 1970-01-01
  • 2022-07-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多