【发布时间】:2022-01-15 16:59:47
【问题描述】:
我希望这些代码的结果相同,但另一个代码有什么问题。
def remove_letters(list):
x = []
for i in range(len(list)):
if type(list[i]) == type(1):
x.append(list[i])
print(x)
return x
y = [1,'b', 'c',2]
remove_letters(y)
Output >> [1,2]
def remove_letters(list):
x = list
for i in range(len(list)):
if type(list[i]) == type('a'):
x.remove(list[i])
print(x)
return x
y = [1,'b', 'c',2]
remove_letters(y)
output>>
Traceback (most recent call last):
File "/Users/genesissales/PycharmProjects/1. Unbuquity [ 1, a, b, 2]/main.py", line 14, in <module>
remove_letters(y)
File "/Users/genesissales/PycharmProjects/1. Unbuquity [ 1, a, b, 2]/main.py", line 6, in remove_letters
if type(list[i]) == type('a'):
IndexError: list index out of range
Process finished with exit code 1
它给出了一个错误。似乎该列表也正在被 for 循环。
【问题讨论】:
-
在迭代列表时从列表中删除应该谨慎!
标签: python-3.x list