2024-04-18 12:21:39 发布
网友
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公司
>>> 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()的项也会删除该元素的第一个出现项,因此可能会出现一些意外的结果。你知道吗
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不知道如何继承。你知道吗
type()
type
示例:
>>> check(['a', 'b', 1]) [1] >>> check([ 1, 'a', 'b', 'c', 2 ]) [1, 2] >>> check(['a', 'b', 'c', 'd']) []
功能如下:
你可以用
输出:
或
输出:
您在迭代列表时正在修改它。它将跳过元素,因为列表在迭代过程中会发生更改。删除带有
list.remove()
的项也会删除该元素的第一个出现项,因此可能会出现一些意外的结果。你知道吗从列表中删除元素的标准方法是构造一个新的列表,如下所示:
或者您可以返回一个常规列表:
通常应该使用^{} 而不是
type()
来测试类型。type
不知道如何继承。你知道吗示例:
相关问题 更多 >
编程相关推荐