将数组中的值求和小于某个值

时间:2015-12-11 00:34:26

标签: python

我有一个带有数字和零的3x3数组。我需要在下一个点ls[i+1]和它之前的点ls[i]之间取绝对差值。以下是我的清单示例:

ls=[(98.6,99,0),(98.2,98.4,97.1),(97.6,0,98.3)]

零是错误的数据。我需要一个循环:

  1. 获取每行中未来数字和当前数字之间的绝对差异,
  2. 使差异大于最大差异零 (max diff=1.9在这种情况下,假设零是有缺陷的数据),
  3. 将每行的差异加在一起,以便我留下一个总和列表。
  4. 现在看来,最终结果将是:

    result=[(0.4,99),(0.2,1.3),(97.6,98.3)]
    

    鉴于零不是好数据,大于1.9的差异不是准确的结果。

3 个答案:

答案 0 :(得分:3)

如果您对将给定的最大差值设置的差异设置为0感到满意,可能会在第二步中实现该逻辑:

ls=[(98.6,99,0),(98.2,98.4,97.1),(97.6,0,98.3)]

unfiltered = [tuple(abs(x1 - x2) for x1, x2 in zip(tup, tup[1:]))
                for tup in ls]
max_diff = 1.9
results = [tuple((x if x < max_diff else 0) for x in tup)
                for tup in unfiltered]

如果您的对象不是本机python列表/元组但支持索引,那么最好这样做:

ls=[(98.6,99,0),(98.2,98.4,97.1),(97.6,0,98.3)]

unfiltered = [tuple(abs(item[i] - item[i+1]) for i in range(len(item)-1))
                for item in ls]
max_diff = 1.9
results = [tuple((x if x < max_diff else 0) for x in tup)
                for tup in unfiltered]

答案 1 :(得分:2)

不确定为什么在做绝对差异时数字会搞砸,可能与浮点数有关...

ls=[(98.6,99,0),(98.2,98.4,97.1),(97.6,0,98.3)]

def abs_diff(lst, max_diff=1.9):
    n = len(lst)
    if n < 2:
        return lst
    res = []
    for i in range(n-1):
        diff = abs(lst[i] - lst[i+1])
        if diff > max_diff:
            res.append(0)
        else:
            res.append(diff)
    return res

result = map(tuple, map(abs_diff, ls)) 
print result
# [(0.40000000000000568, 0), (0.20000000000000284, 1.3000000000000114), (0, 0)]

答案 2 :(得分:1)

这应该是你。我已经打破了你不好的减法/清除不良值,但是你可以递归地遍历列表,随意构建所需的值,过滤掉0

def awkward_subtract(a, b):
    if (a is None) or (b is None) or (a == 0) or (b == 0):
        return 0
    else:
        return abs(a - b)

def compare_lists(ls):     
    head, *tail = ls
    if not tail:
        return [list(filter(int(0).__ne__, head))]
    else:
        values = [awkward_subtract(head[x], tail[0][x]) for x in range(0, len(head))]
        return [list(filter(int(0).__ne__, values))] + compare_lists(tail)

您可以在REPL *中测试它:

>>> ls = [[98.6,99,0],[98.2,98.4,97.1],[97.6,0,98.3]]
>>> compare_lists(ls)
[[0.3999999999999915, 0.5999999999999943], [0.6000000000000085, 1.2000000000000028], [97.6, 98.3]]

(*)我认为你的测试不太对,顺便说一句。

请注意,这样可以轻松使用嵌入式列表,但修复它很简单:

ts = [(98.6,99,0),(98.2,98.4,97.1),(97.6,0,98.3)]
ls = [list(t) for t in ts]