如何在Python中有條件地替換列表值?

Susan Sarandon
發布: 2024-10-17 18:23:31
原創
757 人瀏覽過

How to Replace List Values Conditionally in Python?

Replacing List Values Conditionally in Python

When working with lists, it's often necessary to modify their values based on certain conditions. One common task is to replace values with None if a condition evaluates to True.

Solution Using List Comprehension

The most efficient way to do this is through a list comprehension.

<code class="python">new_items = [x if x % 2 else None for x in items]</code>
登入後複製

Here, items is your original list, and x % 2 checks whether the item is even. If true, it replaces the item with None; otherwise, it keeps the original value.

In-place Modification

While it's possible to modify the original list in-place, it's not recommended for efficiency reasons.

<code class="python">for index, item in enumerate(items):
    if not (item % 2):
        items[index] = None</code>
登入後複製

This approach requires iterating over the entire list twice, which can be costly for large lists.

Timing Comparisons

Benchmarking the two approaches shows that list comprehension is significantly faster, particularly for large lists.

Python 3.6.3:

(In-place) 1.06 µs ± 33.7 ns per loop
(List comprehension) 891 ns ± 13.6 ns per loop
登入後複製

Python 2.7.6:

(In-place) 1.27 µs per loop
(List comprehension) 1.14 µs per loop
登入後複製

以上是如何在Python中有條件地替換列表值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!