Home > Blockchain >  slice list with if else condition using list comprehension
slice list with if else condition using list comprehension

Time:11-07

I want the list to has only number that is not 1 [3,4,5] and put the 1 into another list. below is the code i write

a_list=[1,1,1,1,3,4,5]
one_list=[]
a_list[:] = [a if a != 1 else one_list.append(a) for a in a_list]
print(a_list)
print(one_list)

here is the output for a_list - [None, None, None, None, 3, 4, 5]

my desired output for a_list - [3, 4, 5]

CodePudding user response:

Regarding your first part of the question, the correct comprehension would be:

[e for e in a_list if e != 1]

For what you want to do, a comprehension is not really the right tool, use a classical loop:

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)     

output:

>>> list1
[1, 1, 1, 1]

>>> list2
[3, 4, 5]

what you wanted to do and why you should not:

what you tried to do with the comprehension is:

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

However, you should not as it does not prevent making a temporary list, and it is not explicit/pythonic.

bonus: using 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))

CodePudding user response:

This happens because list.append() is in-place function and return None. You can do what you want like below:

In-place operation is an operation that changes directly the content.

a_list =[1,1,1,1,3,4,5]
one_list = [a for a in a_list if a==1]
a_list = [a for a in a_list if a!=1]
print(a_list)
print(one_list)

Output:

[3, 4, 5]
[1, 1, 1, 1]
  • Related