为什么每次在Python中运行此循环时,列表​​长度都会更改,以仅存储偶数?

我对此完全感到困惑。我正在运行一个FOR循环,该循环标识所有偶数(模除)并存储它们。

但是,每当我在相同的数字列表上运行循环时,列表​​长度会减少吗?我真的不太明白,因为确定所有这些数字都应该在第一次运行循环时删除吗?

我已经复制了下面的代码。

# Sanity check - Modular [remainder] divison in loops

# Python Libraries 
from random import randint

# Create a list of 50 random integers between 0 and 1000
randomNumbers = []
for i in range(100): 
    randomInt = randint(0, 1000) 
    randomNumbers.append(randomInt)
print("List of 50 values: ", randomNumbers,"\n") 

# Remove odd numbers
counter     = 0

for i in randomNumbers: 
    if(i % 2 != 0):
        randomNumbers.remove(i)
counter += 1
print("Loop run: "+str(counter))
print('\t > List length = '+str(len(randomNumbers)))

for i in randomNumbers: 
    if(i % 2 != 0):
        randomNumbers.remove(i)
counter += 1
print("Loop run: "+str(counter))
print('\t > List length = '+str(len(randomNumbers)))

for i in randomNumbers: 
    if(i % 2 != 0):
        randomNumbers.remove(i)
counter += 1
print("Loop run: "+str(counter))
print('\t > List length = '+str(len(randomNumbers)))

任何帮助将非常感激!

编辑:意识到第一次上传是错误的(文件和结构以及所有内容)代码,这是版本。

评论
  • 执着
    执着 回复

    The array evenNumbers remains in memory after each loop.
    The values accumulate, and therefore you see a doubling of the length after the second loop and a tripling after the third loop.

    For more information on the scoping of variables in Python, you can visit see this W3schools page or read the language documentation.

  • 紫云
    紫云 回复

    您一次又一次地使用相同的列表,并且……:)

    # Sanity check - Modular [remainder] divison in loops
    
    # Python Libraries 
    from random import randint
    
    # Create a list of 50 random integers between 0 and 1000
    randomNumbers = []
    for i in range(100): 
        randomInt = randint(0, 1000) 
        randomNumbers.append(randomInt)
    print("List of 50 values: ", randomNumbers,"\n") 
    
    # Remove odd numbers
    evenNumbers = []
    counter     = 0
    
    for i in randomNumbers: 
        if(i % 2 == 0):
            evenNumbers.append(i)
    counter += 1
    print("Loop run: "+str(counter))
    print('\t > List length = '+str(len(evenNumbers)))
    
    # RESET THE LIST
    evenNumbers = []
    
    for i in randomNumbers: 
        if(i % 2 == 0):
            evenNumbers.append(i)
    counter += 1
    print("Loop run: "+str(counter))
    print('\t > List length = '+str(len(evenNumbers)))
    
    # RESET THE LIST
    evenNumbers = []
    
    for i in randomNumbers: 
        if(i % 2 == 0):
            evenNumbers.append(i)
    counter += 1
    print("Loop run: "+str(counter))
    print('\t > List length = '+str(len(evenNumbers)))