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

标签 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']

运行时

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

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

有人能解释一下结果是如何评估的吗.. Thnx

最佳答案

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

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

>>> def check(temp):
...    return list(x for x in temp if not isinstance(x, str))

或者你可以返回一个常规的列表理解:

>>> def check(temp):
...     return [x for x in temp if not isinstance(x, str)]

您通常应该使用 isinstance() 测试类型而不是 type()。例如,type 对继承一无所知。

例子:

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

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

>>> check(['a', 'b', 'c', 'd'])
[]

关于python - 需要澄清 - 使用列表的 Python For 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22778467/

相关文章:

c++ - 我怎样才能写成对的 list ?

c# - 用默认值填充 List<int>?

python - 相对导入在 Python 中不起作用

python - 使用 pandas 或 numpy 将不规则列数据读入 python 3.X

Python Mysql - 查询语法错误

python - 为什么不在 Python 的 subprocess.Popen 中使用 `shell=True`?

python - 列表列表中的组合

regex - 正则表达式中的字节错误

python - Tornado .web : Is there a method which is called after the actual handler method?

将列表转换为类字段的Pythonic方法