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]但是,此方法需要在列表上進行兩個單獨的迭代,這可能是效率低下的。要提高性能,請考慮使用條件附加的手動迭代:
,[],[] 對於mylist中的X: (不好,好)[x in goodvals] .append(x)
在此代碼中:good, bad = [], [] for x in mylist: (bad, good)[x in goodvals].append(x)
emplent element emplance。 goodvals]要根據良好的條件x選擇適當的列表。
此表達式會評估不滿意,如果x不滿足條件,否則否則良好。免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3