将值映射到列表中的其他值

时间:2019-05-28 16:48:26

标签: python

问题是映射特定列表以累积时间。数字的单​​个变化为1 ms。但是,时钟会在数字255之后重设。

list_val = [ 253 ,1,15,27,45,63,120,140,195,210,225,243,2,5,1]

输出应该像

new_list = [ 1 ,3,17,29,47,65,122,142,197,212,227,245,257,260,510].

这是我尝试过的

new_list = []
for i in range(len(list_val)):
      if i == 0:
          new_list.append(1)
      elif list_val[i-1] < list_val[i] :
          new_list[i] =new_list.append(list_val[i] - list_val[i-1] + new_list[i-1])
      elif list_val[i-1] > list_val[i] :
          new_list[i] = new_list.append(255 - list_val[i-1] + new_list[i-1])
      else: #list_val[i-1] == list_val[i]:
          new_list[i] = new_list.append(255 + list_val[i-1] + new_list[i-1])

以下是错误 +不支持的操作数类型:“ int”和“ NoneType”

2 个答案:

答案 0 :(得分:1)

您的语法有误。

调用append方法会将元素添加到原始列表,但返回None。因此,您需要按以下方式调整代码。

new_list = []
for i in range(len(list_val)):
    if i == 0:
        new_list.append(1)
    elif list_val[i-1] < list_val[i] :
        new_list.append(list_val[i] - list_val[i-1] + new_list[i-1])
        # you can replace new_list[i-1] with new_list[-1] if you choose to
    elif list_val[i-1] > list_val[i] :
        new_list.append(255 - list_val[i-1] + new_list[i-1])
    else:
        new_list.append(255 + list_val[i-1] + new_list[i-1])

结果是

new_list = [1, 3, 17, 29, 47, 65, 122, 142, 197, 212, 227, 245, 257, 260, 510]

答案 1 :(得分:0)

那呢:

import numpy as np
list_val = [ 253 ,1,15,27,45,63,120,140,195,210,225,243,2,5,1]
new_list = np.cumsum(np.remainder(np.diff(list_val), 256))

基本上会发生什么:

  • 首先通过numpy diff函数计算差异list_val[i] - list_val[i-1]
  • 通过除以256(以数学术语为模项)除以每个差值的余数,将差值转换为0到255之间的值
  • 对其余部分应用累计金额

PS:我知道结果与期望的输出不完全相同,但是我很难理解为什么总是静态设置前1 ms。