Home >Backend Development >Python Tutorial >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:
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.
The above is the detailed content of How Can I Efficiently Partition a List Based on a Condition?. For more information, please follow other related articles on the PHP Chinese website!