Heim  >  Artikel  >  Backend-Entwicklung  >  Wie ersetze ich Listenwerte bedingt in Python?

Wie ersetze ich Listenwerte bedingt in Python?

Susan Sarandon
Susan SarandonOriginal
2024-10-17 18:23:31758Durchsuche

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

Das obige ist der detaillierte Inhalt vonWie ersetze ich Listenwerte bedingt in Python?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn