在for循环python中迭代两个对象

2024-10-01 13:26:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在for循环中迭代两个范围相同的对象,但是,它显示了一个错误

for (s,s1) in range (5000,10000):
TypeError: cannot unpack non-iterable int object

我的代码是:

(fs, data)=wav.read('13.wav')
frq, X = frequency_sepectrum(data, fs)

y=butter_highpass_filter(data,3000, fs, order=5)        
frqs, Y = frequency_sepectrum(y, fs)

s = set (frq)
s1 = set (frqs)
for (s,s1) in range (5000,10000):
    if (X[s]> 10 and Y[s1]>100):
        print ('yes')
        break

Tags: 对象infordata错误rangefsfrequency
2条回答

我刚刚尝试了我的解决方案:

s = set (frq)
s1 = set (frqs)
for s in range(5000,10000):
    for s1 in range (5000,10000):
        if (X[s]> 10 and Y[s1]>100):
            print ('yes')
            break

运行时间有点长,所以我想知道有没有办法节省执行时间

让我们打开构造for obj in iterable:

Python期望iterable在某种意义上是“类似列表的”:一个列表、字典或类似的东西。在每次循环迭代中,objiterable中“下一个”的值。这里,您的iterablerange(5000,10000),它指的是序列500050015002,…,9999。您的代码出错,因为没有合理的方法将2元组(s,s1)设置为数字,例如5000

我不是100%确定你想要实现什么,但是假设你只想检查5000到10000之间的频率,即只检查那些frq[i] > 5000 && frq[i] < 10000的条目,你需要做一些其他的事情

import numpy as np

(fs, data)=wav.read('13.wav')
frq, X = frequency_sepectrum(data, fs)

y=butter_highpass_filter(data,3000, fs, order=5)        
frqs, Y = frequency_sepectrum(y, fs)

# optional check for if frq, frqs are the same (I assume they are)
for f1, f2 in zip(frq, frqs):
    if f1 != f2:
        print("Frequency grids do not agree.")

# Find the indices of the boundary frequencies,
# assuming that frqs is in ascending order
min_idx = np.searchsorted(frqs, 5000)
max_idx = np.searchsorted(frqs, 10000)

# chop off the extraneous values
frqs = frqs[min_idx : max_idx]
X = X[min_idx : max_idx]
Y = Y[min_idx : max_idx]

# O(n) loop to check for first (lowest-frequency) occurrence of X>10, Y>100
for f, x, y in zip(frq, X, Y):
    if (x> 10 and y>100):
        print ('yes, found at frequency f=', f)
        break

说明:

zip(frq, frqs)将两个向量粘在一起,形成一个元组向量,可以这样想[( , ), ( , ), ( , ), ...]

for f1, f2 in zip(frq, frqs)将f1设置为frq的值,将f2设置为frqs在每个循环迭代中的值

下面的循环做同样的事情,但是有三个向量粘在一起

请注意,如果X, Y, frq, frqs中的任何一个长度与其他长度不同,则此操作将失败/出现意外行为

相关问题 更多 >