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:
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.
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