使用lis的循环需要Python吗

2024-04-18 12:21:39 发布

您现在位置:Python中文网/ 问答频道 /正文

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

什么时候跑步

温度=['a',1],输出为[1]

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

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


Tags: inforoutputifdefchecktype公司
3条回答
>>> 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']

你可以用

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]

您在迭代列表时正在修改它。它将跳过元素,因为列表在迭代过程中会发生更改。删除带有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)]

通常应该使用^{}而不是type()来测试类型。type不知道如何继承。你知道吗

示例:

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

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

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

相关问题 更多 >