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

时间:2014-04-01 06:33:30

标签: 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&#39 ;,2]

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

3 个答案:

答案 0 :(得分:5)

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

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

>>> 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'])
[]

答案 1 :(得分:0)

你可以使用,

def check(temp):
    return [i for i in temp if type(i)!=str]

temp = [ 1, 'a', 'b', 'c', 2 ]

print check(temp)

输出:

[1, 2]

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

temp = [ 1, 'a', 'b', 'c', 2 ,"e",4,5,6,7]

print check(temp)

输出:

[1, 2, 4, 5, 6, 7]

答案 2 :(得分:0)

>>> text = ['a', 'b', 1, {}]
>>> filter(lambda x: type(x) == str, text)
['a', 'b']

功能将如下:

>>> def check(temp):
...     return list(filter(lambda x: type(x) == str, temp))
... 
>>> check(text)
['a', 'b']