简体   繁体   English

如何在python中声明变量?

[英]How variables are declared in python?

I guess something is wrong with this I believe. 我认为这是有问题的。 I have an array of data set I'm trying to perform some analysis on. 我正在尝试执行一些分析的数据集数组。 This is what I want to do. 这就是我要做的。 Say for example the following is the array 例如说以下是数组

signal=[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1...] , I want to take the data points 0:3 stored somewhere, I need them and also replace those 0:3 with zeros. signal=[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1...] ,我想获取存储在某处的数据点0:3 ,我需要它们,也替换那些0:3与零。 This is how I did it but the final result comes out right but the stored 0:3 data points stored also come out to be zeros. 这是我的方法,但是最终结果正确,但是存储的0:3数据点也变成了零。 Can anyone help me out here. 有人可以帮我从这里出去吗。 I thought it was something simple to do but I have been battling with this for the past couple of days. 我认为这很简单,但是过去几天我一直在与之作斗争。 Thanks in advance! 提前致谢!

here is my code: 这是我的代码:

n = len(signal)

for i in range(n):

    first_3points = signal[0:3]

    signal[0:3] = 0

    trancated_signal = signal

I will be very glad to see where I went wrong! 看到我哪里出错了,我将感到非常高兴!

It looks like your application is better served with numpy, which is well-developed to work with arrays representing signal samples. 看起来numpy可以更好地服务于您的应用程序,而numpy可以很好地与表示信号样本的数组一起使用。 You may already be using numpy, since if signal is a list, the assignment signal[0:3] = 0 raises a TypeError . 您可能已经在使用numpy了,因为如果signal是一个列表,则分配signal[0:3] = 0会引发TypeError Here's how I'd do it using numpy: 这是我使用numpy的方法:

import numpy as np
N = 256
signal = np.ones(N)
first3 = signal[0:3].copy()
signal[0:3] = 0

Note that if you don't make first3 a copy of the first elements in signal , it just becomes a view into signal , and when you change elements in signal , you also change first3 . 请注意,如果你不使first3第一元素的副本signal ,它只是成为一个视图到signal ,而当你改变元素signal ,也改变first3 If I understand your question correctly, you are trying to save the original elements from signal in first3 before you change them. 如果我正确理解了您的问题,则您尝试在更改它们之前在first3保存signal中的原始元素。

Using ordinary lists instead of numpy this is quite simple: 使用普通列表而不是numpy,这非常简单:

signal = [1] * 20
first_3_points = signal[:3]
signal[:3] = [0] * 3

The loop in your original code appears to be unnecessary. 原始代码中的循环似乎是不必要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM