Maison  >  Article  >  développement back-end  >  Comment remplacer conditionnellement les valeurs de liste en Python ?

Comment remplacer conditionnellement les valeurs de liste en Python ?

Susan Sarandon
Susan Sarandonoriginal
2024-10-17 18:23:31758parcourir

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

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn