Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list comprehension to create unequal length lists from a list using conditional

Using list comprehension, itertools or similar functions, is it possible to create two unequal lists from one list based on a conditional? Here is an example:

main_list = [6, 3, 4, 0, 9, 1]
part_list = [4, 5, 1, 2, 7]

in_main = []
out_main = []

for p in part_list:
    if p not in main_list:
        out_main.append(p)
    else:
        in_main.append(p)

>>> out_main
[5, 2, 7]

>>> in_main
[4, 1]

I'm trying to keep it simple, but as an example of usage, the main_list could be values from a dictionary with the part_list containing dictionary keys. I need to generate both lists at the same time.

like image 751
Henry Thornton Avatar asked Dec 20 '25 05:12

Henry Thornton


2 Answers

So long as you have no repeating data & order doesn't matter.

main_set = set([6, 3, 4, 0, 9, 1])
part_set = set([4, 5, 1, 2, 7])

out_main = part_set - main_set
in_main = part_set & main_set

Job done.

like image 51
Jakob Bowyer Avatar answered Dec 22 '25 19:12

Jakob Bowyer


If the order (within part_list) is important:

out_main = [p for p in part_list if p not in main_list]
in_main = [p for p in part_list if p in main_list]

otherwise:

out_main = list(set(part_list) - set(main_list))
in_main = list(set(part_list) & set(main_list))
like image 42
eumiro Avatar answered Dec 22 '25 18:12

eumiro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!