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.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With