"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > input: How Can I Efficiently Partition a List Based on a Condition? output: How to efficiently split lists based on conditions?

input: How Can I Efficiently Partition a List Based on a Condition? output: How to efficiently split lists based on conditions?

Posted on 2025-04-14
Browse:514

How Can I Efficiently Partition a List Based on a Condition?

Partitioning Lists Based on Conditions

When splitting a list into two based on a given condition, it's tempting to iterate over the list twice, creating two new lists as follows:

good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]

However, this approach requires two separate iterations over the list, which can be inefficient. To improve performance, consider using a manual iteration with conditional appending:

good, bad = [], []
for x in mylist:
    (bad, good)[x in goodvals].append(x)

In this code:

  • We initialize two empty lists, good and bad, to store the partitioned elements.
  • We iterate over the elements of mylist.
  • For each element x, we use the expression (bad, good)[x in goodvals] to select the appropriate list based on the condition x in goodvals.
  • This expression evaluates to bad if x does not meet the condition and good otherwise.
  • We append x to the selected list using the append method.

This approach avoids the need for two separate iterations, improving performance by reducing the number of list traversals from two to one. It is also considered more elegant, as it captures the partitioning logic in a concise and readable manner.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3