【问题标题】:Using non integer values as in a function在函数中使用非整数值
【发布时间】:2013-12-28 13:11:37
【问题描述】:

我收到此错误:'TypeError: list indices must be integers, not float'
但是我使用的函数需要接受非整数值,否则我的结果会有所不同...
只是为了给您一个想法,我编写了一些代码,这些代码将高斯拟合到具有单个峰值的某些数据。为此,我需要计算 sigma 的估计值。为此,我编写了两个用于查看数据的函数,使用峰值的 x 值来找到两个点(r_pos 和 l_pos),它们位于峰值的任一侧并与 y 轴保持一定距离(脱粒)。从中我可以得到一个估计的 sigma(r_pos - l_pos)。
这一切都来自一段有效的代码,但是我的课程作业的标记表说我需要使用函数,所以我试图把它变成:

I0 = max(y)
pos = y.index(I0) 
print 'Peak value is',I0,'Counts per sec at' ,x[pos], 'degrees(2theta)'
print pos,I0
#left position
thresh = 10
i = pos
while y[i] > thresh:
    i -= 1
l_pos = x[i]
#right position
thresh = 10
i = y.index(I0)
while y[i] > thresh:
    i += 1
r_pos = x[i]
print r_pos
sigma0 = r_pos - l_pos
print sigma0

使用可以调用的函数等。这是我的尝试:

def Peak_Find(x,y):
    I0 = max(y)
    pos = y.index(I0)
    return I0, x[pos]

def R_Pos(thresh,position):
    i = position    
    while y[i] > thresh:
        i += 0.1
    r_pos = x[i]
    return r_pos

peak_y,peak_x = Peak_Find(x,y)
Right Position = R_Pos(10,peak_x)

peak_y = 855.0 顺便说一下,Peak_x = 32.1

【问题讨论】:

  • 我敢肯定,在接下来的 5 秒内,您将有大约 6 个 cmets 请求代码 ;-),所以我会继续努力的 -- 你能发布代码吗(最少演示问题的示例)和预期的输入/输出?
  • 即使没有看到代码,我也可以告诉您,您正在使用浮点数作为列表索引。不要那样做。
  • 您需要告诉我们函数对这些非整数值做了什么,以及为什么您尝试将它们用作一个索引,然后我们才能告诉你你需要做什么来修复它。也许您需要使用int(x)round(x) 作为索引,或者您可能需要使用字典而不是列表,或者您可能需要编写代码在值之间进行插值,或者......我们怎么可能知道没有知道你想做什么吗?
  • 您希望y[32.1] 会返回什么?!
  • 如果您正在寻找介于数据点之间的值,您需要查看插值。您在这里尝试的简单方法没有成功的机会。

标签: python function integer typeerror


【解决方案1】:

看来你想换行

i = position 

类似的东西

i = x.index(position)

因为position 是一个浮点数,并且您想要position 数组中的位置。您正在使用 i 获取数组的索引,并且您必须使用 ints 来执行此操作,因此使用 .index 方法返回数组中的(整数)位置.


最好用这种方式编写程序,因为这样变量名实际上会匹配变量中包含的内容。

def Peak_Find(x,y):
    I0 = max(y)
    pos = y.index(I0)
    return I0, pos

def R_Pos(thresh,position):
    while y[position] > thresh:
        position += 1 # Not sure if this is what you want
    r_pos = x[position]
    return r_pos # Not sure what you want here... this is the value at x, not the position

【讨论】:

  • 我想你误会了。问题是您不能用浮点数索引序列,因为根据定义,索引(在这种情况下)必须是整数。
  • @HannesOvrén 如果您在换行符之前阅读该部分,我指出您不能使用position,因为它是浮点数,而不是整数。让我添加一个句子以明确表示我在说这个。
  • 那为什么你的最后一段代码会做y[position]position += 0.1
  • 啊,我错过了。让我编辑。那里可能也应该是一个整数:)
猜你喜欢
  • 1970-01-01
  • 2017-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-26
  • 2018-10-15
  • 2017-12-29
相关资源
最近更新 更多