简体   繁体   English

第二个变量如何在“for i, j in enumerate”与 list[i] 中工作

[英]How does the second variable work in "for i, j in enumerate" vs list[i]

I understand that it is for 'index', 'value' in enumerate, I thought that I could use the second variable as list[index] but it doesn't seem to work as such, I was wondering what the difference was.我知道它是用于枚举中的“索引”、“值”,我认为我可以将第二个变量用作列表[索引],但它似乎并没有这样工作,我想知道有什么区别。

codeCopy = [1,2,1,1]
currentSequence = [2,1,2,2]
correctColor = 0

for i, n in enumerate(codeCopy):
    for a, b in enumerate(currentSequence):
        if n == b:
            correctColor += 1
            n = None
            b = None
            print("i:",i, a)
            break
            
print(currentSequence)
print(codeCopy)

which outputs their original values instead of their new value of 'None' but if I replace它输出它们的原始值而不是它们的新值“无”但是如果我替换

n = None
b = None

to

codeCopy[i] = None
currentSequence[a] = None

It turns them accordingly to 'None'它相应地将它们变为“无”

which outputs their original values instead of their new value of 'none'它输出它们的原始值而不是它们的新值“无”

It's not supposed to do that.它不应该那样做。 The values n and b , as returned by enumerate , are pointers to the objects, but setting them to None only changes what those variable names reference, rather than the actual object itself. enumerate返回的值nb是指向对象的指针,但将它们设置为None只会更改这些变量名引用的内容,而不是实际的 object 本身。 (You'll have to use memcpy -type magic to achieve this.) (你必须使用memcpy类型的魔法来实现这一点。)

Think of it like this:可以这样想:

>>> a = ['my', 'reference', 'to', 'a', 'list']
>>> b = a
>>> b[0] = 'this also changes a'  # b references the same object at a
>>> a
['this also changes a', 'reference', 'to', 'a', 'list']
>>> b = None  # this overwrites what b points to; it does not affect a
>>> a
['this also changes a', 'reference', 'to', 'a', 'list']

Suppose the program, in memory, looks like this:假设在 memory 中的程序如下所示:

address | value
100     | ['my', 'reference', 'to', 'a', 'list']  
101     | a -> 100 (list)
102     | b -> 100 (list)

When you change b , it doesn't actually affect the actual object:当您更改b时,它实际上不会影响实际的 object:

address | value
100     | ['my', 'reference', 'to', 'a', 'list']  
101     | a -> 100 (list)
102     | b -> 103 (None)  # does NOT set the value at 100 to None
103     | None  # implementation detail: small integers and None and other things are permanently kept somewhere in memory at initialization

If you want to modify the value that's actually at the list, you need to do the_list[desired_index] = None .如果你想修改列表中的实际值,你需要做the_list[desired_index] = None

from https://docs.python.org/3/library/functions.html#enumerate来自https://docs.python.org/3/library/functions.html#enumerate

Equivalent to:相当于:

 def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1

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

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