需要澄清 - Python For循环使用列表

1 python list python-3.x

def check(temp):
  for i in temp:
    if type(i) == str:
      temp.remove(i)

temp = ['a', 'b']
print(temp)    ==> Output: ['a','b']
check(temp)
print(temp)    ==> Output: ['b']
Run Code Online (Sandbox Code Playgroud)

在运行时

temp = ['a',1],输出为[1]

temp = [1,'a','b','c',2],输出为[1,'b',2]

有人可以解释如何评估结果.. Thnx

msv*_*kon 5

您正在迭代它时修改列表.它将跳过元素,因为列表在迭代期间会发生变化.删除项目list.remove()也将删除该元素的第一个出现,因此可能会有一些意外的结果.

从列表中删除元素的规范方法是构造一个列表,如下所示:

>>> def check(temp):
...    return list(x for x in temp if not isinstance(x, str))
Run Code Online (Sandbox Code Playgroud)

或者您可以返回常规列表理解:

>>> def check(temp):
...     return [x for x in temp if not isinstance(x, str)]
Run Code Online (Sandbox Code Playgroud)

您通常应该测试类型isinstance()而不是type().type例如,他不知道继承.

例子:

>>> check(['a', 'b', 1])
[1]

>>> check([ 1, 'a', 'b', 'c', 2 ])
[1, 2]

>>> check(['a', 'b', 'c', 'd'])
[]
Run Code Online (Sandbox Code Playgroud)