环路替代列表理解。它仍然修改列表。正如其他人指出x is 0
简化的区别0
和False
之间:
In [106]: al=[0, 1, 2, False, True, 3,0,10]
In [107]: for i,x in enumerate(al):
...: if x is 0:
...: value = al.pop(i)
...: al.append(value)
...:
In [108]: al
Out[108]: [1, 2, False, True, 3, 10, 0, 0]
副作用就是这样,一环比一的理解更好。理解应该用在:
return [.... for x in al if ...]
有意义。你也可以在理解中使用枚举:
return [fun(x, i) for i, x in enumerate(al) if x...]
在明确的列表理解中,列表只会出现一次;测试和返回值将仅取决于迭代变量,而不取决于原始列表。
===================
要注意的是0
和False
常常被当作是相同的。对于那些希望把数字作为False
0
,并且True
为1以及期待布尔将把0
为False
功能的示例操作。在列表理解与and
In [117]: [x+1 for x in al]
Out[117]: [1, 2, 3, 1, 2, 4, 1, 11]
In [118]: al=[0, 1, 2, False, True, 3,0,10]
In [119]: sum(al)
Out[119]: 17
=================
实施例:
In [137]: [x for x in al if x==0]
Out[137]: [0, False, 0]
In [138]: [x for x in al if x==0 and x is not False]
Out[138]: [0, 0]
In [140]: [x for x in al if not (x==0 and x is not False)]
Out[140]: [1, 2, False, True, 3, 10]
======== ====
另一种可能的测试 - 的STR表示的:
In [143]: [x for x in al if str(x)!='0']
Out[143]: [1, 2, False, True, 3, 10]
================
您的问题不在测试中,而是在al.index(x)
;它匹配0
和False
,并删除第一个,而不管哪个x
正在通过您的测试。
版本与al.index(x)
:
In [396]: al=[1,False,2, 0,3,"b"]
In [397]: for x in al:
...: if x ==0 and x is not False:
...: al.append(al.pop(al.index(x)))
...:
In [398]: al
Out[398]: [1, 2, 0, 3, 'b', False]
版本并具有枚举i
In [399]: al=[1,False,2, 0,3,"b"]
In [400]: for i,x in enumerate(al):
...: if x ==0 and x is not False:
...: al.append(al.pop(i))
...:
In [401]: al
Out[401]: [1, False, 2, 3, 'b', 0]
或者在你的函数:
def move_zeros(array):
[array.insert(len(array), array.pop(i)) for i,x in enumerate(array) if (x == 0 and x is not False)]
return array
In [403]: al=[1,False,2, 0,3,"b"]
In [404]: move_zeros(al)
Out[404]: [1, False, 2, 3, 'b', 0]
隔离测试index
:
In [405]: al=[1,False,2, 0,3,"b"]
In [406]: al.index(0)
Out[406]: 1
In [407]: al.index(False)
Out[407]: 1
您能详细说明一下您的函数在做什么吗?顺便说一句,你正在创建一个'None'的数组,因为insert不会返回一个值。 'array.insert(len(array),...)'与'array.append(...)'相同。 – ozgur
你应该学会使用列表解析。这不是他们如何使用。快速经验法则:如果您的列表理解有副作用,那么您做错了。 – spectras
添加一个'array'(列表,我假设)给你的问题。你想要什么结果。你应该“返回”列表理解,而不是在理解中被修改的列表。 – hpaulj