关于你问题的第一部分,正确的理解是:
[e for e in a_list if e != 1]
对于您想要做的事情,理解并不是真正正确的工具,请使用经典循环:
a_list=[1,1,1,1,3,4,5]
list1 = []
list2 = []
for e in a_list:
if e == 1:
list1.append(e)
else:
list2.append(e)
输出:
>>> list1
[1, 1, 1, 1]
>>> list2
[3, 4, 5]
你想做什么以及为什么不应该做:
你试图用理解做的是:
a_list=[1,1,1,1,3,4,5]
one_list = []
a_list[:] = [e for e in a_list if (True if e != 1 else one_list.append(e))]
a_list, one_list
但是,您不应该这样做,因为它不会阻止制作临时列表,而且它不是显式/pythonic。
奖励:使用 itertools
from itertools import tee, filterfalse
def partition(pred, iterable):
"Use a predicate to partition entries into false entries and true entries"
# partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
t1, t2 = tee(iterable)
return filterfalse(pred, t1), filter(pred, t2)
a_list=[1,1,1,1,3,4,5]
a_list, one_list = map(list, partition(lambda x: x == 1, a_list))