【问题标题】:Counting elements of an array in Python [closed]在Python中计算数组的元素[关闭]
【发布时间】:2020-12-06 19:25:20
【问题描述】:

我一直在寻找一个练习的答案。 这个练习给了我们一个数字在 -1 和 1 之间的数组。 我们被要求计算信号阵列改变符号的次数。 例如:你有这个数组: [0.7,0.5,0.6,-0.1,0.9,0.6,0.4,-0.2,-0.3,0.2,0.3,-0.3,-0.9,-0.7,0.1,0.2] 它改变标志7次 这是我编写的代码,它应该得到它改变标志的次数的“计数”。 由于某种原因,它不起作用,最后的计数等于 0,它应该是 7。 你能帮我吗 ? 非常感谢。

--代码--

import numpy as np

def zeroCrossing(signal):

    j=0
    ls=len(signal)
    print(ls)
    count=0
    x=0
    y=0
    for j in range(0,ls):
        if signal[j]>0 and x==1:
            j=j+1
            y=0
        elif signal[j]>0 and x==0:
            count==count+1
            x=1
            j=j+1
        elif signal[j]<0 and y==1:
            j=j+1
            x=0
        elif signal[j]<0 and y==0:
            count==count+1
            y=1
            j=j+1
    
    return count

print(zeroCrossing(np.array([0.7,0.5,0.6,-0.1,0.9,0.6,0.4,-0.2,-0.3,0.2,0.3,-0.3,-0.9,-0.7,0.1,0.2])))

【问题讨论】:

  • 看来你把初始数字算作符号的“变化”?
  • 用你自己的话来说,你希望count==count+1做什么?
  • 答案肯定是 6,而不是 7?
  • arr = np.array([0.7,0.5,0.6,-0.1,0.9,0.6,0.4,-0.2,-0.3,0.2,0.3,-0.3,-0.9,-0.7,0.1,0.2]); print(sum(np.where(np.sign(arr) != np.sign(np.roll(arr, -1)), 1, 0))) 会这样做,但我不知道 7 来自哪里
  • 这能回答你的问题吗? Python - counting sign changes

标签: python arrays numpy count return-value


【解决方案1】:

你可以通过简单地遍历数组来实现你想要的,如下所示:

sign_changes = 0
last_number = None
for n in my_array:
    if n < 0: # checks if n is negative
        if last_number != "negative": # checks if the last number was not negative
            sign_changes += 1
        last_number = "negative"
    else: # takes n as positive (including 0)
        if last_number != "positive": # checks if the last number was not positive
            sign_changes += 1
        last_number = "positive"

编辑:

此代码将在 OP 给出的示例数组中计数 7,正如 OP 所期望的那样,它将第一个数字计为“符号更改”。为了避免这种情况(而是计算 6 个符号更改),可以对代码进行一些小的调整。最简单的是将last_number != "positive"last_number != "negative"条件分别改为last_number == "negative"last_number == "positive"

【讨论】:

  • 如果他们要使用数组,那么这速度太慢了
  • 它是否“无望”取决于脚本/程序的确切目标。这是一个简单的解决方案,效果很好并回答了问题。 OP 没有指定任何高性能要求。
【解决方案2】:

您没有修改count 变量,因为您使用比较运算符而不是赋值。将count==count+1 替换为count=count+1 以修复它。

【讨论】:

    【解决方案3】:

    由于你总是将第一个数字计为 1 次,你可以试试这个 numpy 代码:

    arr = np.array([0.7,0.5,0.6,-0.1,0.9,0.6,0.4,-0.2,-0.3,0.2,0.3,-0.3,-0.9,-0.7,0.1,0.2])
    change_count = np.count_nonzero(np.diff(np.sign(arr))) + 1
    
    Out[122]: 7
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 2010-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多