简体   繁体   English

'int' object 不可迭代,map() 通过列表传递

[英]'int' object is not iterable, map() passing trough a list

So lets I have this list;所以让我有这个清单;

yy=[1,2,3,4,5,6,7,8,9,10]

and I want a map() to go through the list using the np.std() this,我想要一个 map() 到 go 通过列表使用 np.std() 这个,

np. std(1,2,3), std(2,3,4), std(3,4,5).... std(8,9,10)

so I thought of doing something like this,所以我想做这样的事情,

import numpy as np
y = [1,2,3,4,5,6,7,8,9,10]
n = 3
x = map(lambda w, n: np.std(y[x-n:x]), range(n,len(y)), n)
print(list(x))

But I get this error 'int' object is not iterable, how do I fix this?但是我得到这个错误'int' object is not iterable,我该如何解决这个问题?

You're passing too many iterables to map .您将太多的迭代传递给map You just need to pass the start index for each piece of the list that you want to np.std()您只需将要传递给np.std()的每个列表的起始索引

import numpy as np
y = [1,2,3,4,5,6,7,8,9,10]
n = 3
x = map(lambda i: np.std(y[i:i+n]), range(len(y) - n)) # pass only the start index for each iteration
print(list(x))

Result:结果:

[0.816496580927726, 0.816496580927726, 0.816496580927726, 0.816496580927726, 0.816496580927726, 0.816496580927726, 0.816496580927726]

OK, now I see what you were trying to do.好的,现在我明白你想要做什么了。 You expected the single value of n to be passed each time into your lambda function.您希望每次将n的单个值传递到 lambda function 中。 But that's not how map works, it expects all its arguments to be iterables.但这不是map的工作方式,它希望其所有 arguments 都是可迭代的。

You had another problem, you are passing w into your lambda function but trying to use it as x .您还有另一个问题,您正在将w传递给您的 lambda function 但试图将其用作x

Here's the version of your code with those two problems fixed:这是修复了这两个问题的代码版本:

x = map(lambda w, n: np.std(y[w-n:w]), range(n,len(y)), [n]*len(y))

You can simplify it by realizing that you don't need to pass n into the lambda function at all, it's already defined in the scope where you're creating the function. You can simplify it by realizing that you don't need to pass n into the lambda function at all, it's already defined in the scope where you're creating the function.

x = map(lambda w: np.std(y[w-n:w]), range(n,len(y)))

Finally you can use a generator expression instead of map .最后,您可以使用生成器表达式代替map

x = (np.std(y[w-n:w]) for w in range(n,len(y)))

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

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