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

``````# 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)))
``````