gpt4 book ai didi

python - 类型错误 : can only concatenate tuple (not "list") to tuple"

转载 作者:太空狗 更新时间:2023-10-29 20:38:16 25 4
gpt4 key购买 nike

我编写了一个简单的脚本来模拟基于每用户平均收入 (ARPU)、利润率和客户保持客户的年数 (ltvYears) 的客户生命周期值(value) (LTV)。下面是我的脚本。它在“ltvYears = ltvYears + [ltv_loop]”这一行抛出错误。错误信息是“TypeError: can only concatenate tuple (not "list") to tuple”。有人能告诉我是什么原因造成的吗?我怀疑问题可能源于“ltvYears = ('f',[])”,我在其中添加了类型代码以消除另一个错误(将 float 乘以 int)。

我是 Python 的新手,所以这段代码很可能是初学者的错误。

lowYears = 0
highYears = 20
modeYears = 3
ARPU = 65.0*12.0
MARGIN = .30
ltvYears = ('f',[])
ltv = []

def ltv(arpu, years, margin):
return arpu * years * margin

N = 10000
for n in range(N):
#estimate LTV
ltv_loop = random.triangular(lowYears, highYears, modeYears)
ltvYears = ltvYears + [ltv_loop]
ltv = ltv + [ltv(ARPU, ltvYears, MARGIN)]

show = 0

if (show==1):
#plot ltv histogram
plt.hist(ltv,bins=10)
plt.title("LTV Probability Density")
plt.xlabel("")
plt.ylabel("$")
plt.show()

编辑 - 这是我的变量的屏幕截图。 enter image description here

EDIT2 ---感谢下面的帮助,我找到了解决方案。一共有三个问题:

  1. 我错误地为变量和函数分配了相同的名称(+1 @autopopulated 指出了这一点)
  2. 这一行是无关的“ltvYears = ltvYears + [ltv_loop]”
  3. 这一行应该使用“ltv_loop”作为第二个参数“ltv = ltv + [calculateltv(ARPU, ltv_loop, MARGIN)]”

+1 @DonCallisto 和@RikPoggi 对项目 2 和 3 的帮助

最佳答案

ltvYears 是一个元组,它的定义如下

ltvYears = ('f',[])

所以说到这一行:

ltvYears = ltvYears + [ltv_loop]

Python 不知道该怎么做,因为您的错误清楚地表明:

"TypeError: can only concatenate tuple (not "list") to tuple"

不清楚该行的行为应该是什么,因此很难提出解决方案。

也许您只需要将 ltvYears 定义为 list 并调用 .append 方法。


编辑

Here OP 说:

ltvYears = ('f',[]) I added the 'f' to indicate that the array is to contain floats. Before I did this I was getting an error about multiplying floats and ints.

你不需要那样做。 Python 不是 C。

只是做:

ltvYears = []

及以后:

ltvYears.append(ltv_loop)

关于python - 类型错误 : can only concatenate tuple (not "list") to tuple",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10506904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com