枚举功能

时间:2016-03-03 05:25:03

标签: python list python-3.x enumerate

有人可以向我解释一下。

所以,我有一个列表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

3 个答案:

答案 0 :(得分:3)

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]

答案 1 :(得分:2)

从python docs,枚举的实现如下:

def enumerate(collection):
    'Generates an indexed series:  (0,coll[0]), (1,coll[1]) ...'     
    i = 0
    it = iter(collection)
    while 1:
        yield (i, it.next())
        i += 1

因为它使用&#39; yield&#39;,它是一个生成器,当你在行中迭代它时存储状态

for i,j in z

要仅使用一个枚举,请将生成器的值转换为列表并重用列表:

s= [-1, 0.5, 0.2, -0.9]

z = list(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)

print(y1)
print(y2)

输出:

[0, 3]
[1, 2]

答案 2 :(得分:2)

enumerate是一个懒惰的生成器,一旦被调用并一直遍历它就完成了。所以,我认为最好直接在for循环中包含其调用:

s= [-1, 0.5, 0.2, -0.9]

y1 = []
for i,j in enumerate(s):
    if -1 <= j <= -0.8: 
        y1.append(i)

y2 = []
for i,j in enumerate(s):
    if -0.8 <= j <= 0.8:
        y2.append(i)

旁注:

if j<=-0.8 and j>=-1:可以替换为if -1 <= j <= -0.8: