谁能给我解释一下。
所以,我有一个列表 s
,其中的数字从 -1 到 1,我想提取列表中某些数字的位置。
例子:
s= [-1, 0.5, 0.2, -0.9]
z = enumerate(s)
y1 = []
for i,j in z:
if j<=-0.8 and j>=-1:
k = i
y1.append(k)
y2 = []
for i,j in z:
if j<=0.8 and j>=-0.8:
k = i
y2.append(k)
我得到 y1 = [0, 3]
和 y2 = []
但是如果我定义第二个 enumerate
:
z1 = enumerate(s)
y1 = []
for i,j in z1:
if j<=-0.8 and j>=-1:
k = i
y1.append(k)
z2 = enumerate(s)
y2 = []
for i,j in z2:
if j<=0.8 and j>=-0.8:
k = i
y2.append(k)
我得到结果 y1 = [0, 3]
和 y2 = [1, 2]
为什么我需要第二个enumerate
?
enumerate
返回序列的迭代器。一旦遍历,就不能再次使用:
In [1]: l = [1, 2, 3, 4, 5]
In [2]: e = enumerate(l)
In [3]: e
Out[3]: <enumerate at 0x7fad7aea25e8>
In [4]: list(e)
Out[4]: [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
In [5]: list(e)
Out[5]: []
你可以用一个列表来包装它:
In [6]: e = list(enumerate(l))
In [7]: e
Out[7]: [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
In [8]: list(e)
Out[8]: [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
In [9]: list(e)
Out[9]: [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
您还可以使用列表理解来简化您的解决方案:
y1 = [i for i, x in enumerate(s) if -1 <= x <= -0.8]
y2 = [i for i, x in enumerate(s) if -0.8 <= x <= 0.8]
我是一名优秀的程序员,十分优秀!