Как заменить значения в списке в Python
Часто вас может заинтересовать замена одного или нескольких значений в списке в Python.
К счастью, это легко сделать в Python, и в этом руководстве дается несколько различных примеров того, как это сделать.
Пример 1. Замена одного значения в списке
Следующий синтаксис показывает, как заменить одно значение в списке в Python:
Пример 2. Замена нескольких значений в списке
Следующий синтаксис показывает, как заменить несколько значений в списке в Python:
Пример 3. Замена определенных значений в списке
Следующий синтаксис показывает, как заменить определенные значения в списке в Python:
Вы также можете использовать следующий синтаксис для замены значений, превышающих определенный порог:
Точно так же вы можете заменить значения, которые меньше или равны некоторому порогу:
Find and replace string values in list [duplicate]
The community reviewed whether to reopen this question 8 months ago and left it closed:
Original close reason(s) were not resolved
I got this list:
What I would like is to replace [br] with some fantastic value similar to <br /> and thus getting a new list:
6 Answers 6
You can use, for example:
Beside list comprehension, you can try map
In case you’re wondering about the performance of the different approaches, here are some timings:
as you can see for such simple patterns the accepted list comprehension is the fastest, but look at the following:
This shows that for more complicated substitutions a pre-compiled reg-exp (as in 9-10 ) can be (much) faster. It really depends on your problem and the shortest part of the reg-exp.
An example with for loop (I prefer List Comprehensions).
If performance is important, including an if-else clause improves performance (by about 5% for a list of 1mil strings, no negligible really).
map() implementation can be improved by calling replace via operator.methodcaller() (by about 20%) but still slower than list comprehension (as of Python 3.9).
If it suffices to modify the strings in-place, a loop implementation may be the fastest.
Python: Replace Item in List (6 Different Ways)
In this tutorial, you’ll learn how to use Python to replace an item or items in a list. You’l learn how to replace an item at a particular index, how to replace a particular value, how to replace multiple values, and how to replace multiple values with multiple values.
Being able to work with lists is an important skill for any Python developer, given how prevalent and understandable these Python data structures are.
By the end of this tutorial, you’ll have learned:
- How to use list assignment to replace an item in a Python list
- How to use for loops and while loops to replace an item in a Python list
- How to replace multiple items in a list
Table of Contents
Replace an Item in a Python List at a Particular Index
Python lists are ordered, meaning that we can access (and modify) items when we know their index position. Python list indices start at 0 and go all the way to the length of the list minus 1.
You can also access items from their negative index. The negative index begins at -1 for the last item and goes from there. To learn more about Python list indexing, check out my in-depth overview here.
If we want to replace a list item at a particular index, we can simply directly assign new values to those indices.
Let’s take a look at what that looks like:
In the next section, you’ll learn how to replace a particular value in a Python list using a for loop.
Want to learn how to use the Python zip() function to iterate over two lists? This tutorial teaches you exactly what the zip() function does and shows you some creative ways to use the function.
Replace a Particular Value in a List in Python Using a For Loop
Python lists allow us to easily also modify particular values. One way that we can do this is by using a for loop.
One of the key attributes of Python lists is that they can contain duplicate values. Because of this, we can loop over each item in the list and check its value. If the value is one we want to replace, then we replace it.
Let’s see what this looks like. In our list, the word apple is misspelled. We want to replace the misspelled version with the corrected version.
Let’s take a look at what we’ve done here:
- We loop over each index in the list
- If the index position of the list is equal to the item we want to replace, we re-assign its value
In the next section, you’ll learn how to turn this for loop into a Python list comprehension.
Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.
Replace a Particular Value in a List in Python Using a List Comprehension
One of the key attributes of Python list comprehensions is that we can often turn for loops into much shorter comprehensions. Let’s see how we can use a list comprehension in Python to replace an item in a list.
We’ll use the same example we used in the for loop, to help demonstrate how elegant a Python list comprehension can be:
We can see here that there are two main benefits of list comprehensions compared to for loops:
- We don’t need to initialize an empty list
- The comprehension reads in a relatively plain English
In the next section, you’ll learn how to change all values in a list using a formula.
Want to learn more about Python list comprehensions? Check out this in-depth tutorial that covers off everything you need to know, with hands-on examples. More of a visual learner, check out my YouTube tutorial here.
Change All Values in a List in Python Using a Function
Neither of the approaches above are immediately clear as to what they are doing. Because of this, developing a formula to do this is a helpful approach to help readers of your code understand what it is you’re doing.
Let’s take a look at how we can use the list comprehension approach and turn it into a formula:
Here, we simply need to pass in the list, the item we want to replace, and the item we want to replace it with. The function name makes it easy to understand what we’re doing, guiding our readers to better understand our actions.
In the next section, you’ll learn how to replace multiple values in a Python list.
Replace Multiple Values in a Python List
There may be many times when you want to replace not just a single item, but multiple items. This can be done quite simply using the for loop method shown earlier.
Let’s take a look at an example where we want to replace all known typos in a list with the word typo .
Similar to the for loop method shown earlier, we check whether or not an item is a typo or not and replace its value.
In the next section, you’ll learn how to replace multiple values in a Python list with different values.
Replace Multiple Values with Multiple Values in a Python List
The approach above is helpful if we want to replace multiple values with the same value. There may be times where you want to replace multiple values with different values.
Looking again at our example, we may want to replace all instances of our typos with their corrected spelling. We can again use a for loop to illustrate how to do this.
Instead of using a single if statement, we’ll nest in some elif statements that check for a value’s value before replacing.
Need to check if a key exists in a Python dictionary? Check out this tutorial, which teaches you five different ways of seeing if a key exists in a Python dictionary, including how to return a default value.
Conclusion
In this tutorial, you learned how to use Python to replace items in a list. You learned how to use Python to replace an item at a particular index, how to replace a particular value, how to modify all values in a list, and how to replace multiple values in a list.
To learn more about Python list indexing, check out the official documentation here.
Метод replace() в Python
Статьи
Введение
В ходе данной статьи мы научимся использовать метод replace() в языке программирования Python.
Метод replace() в Python
Метод replace() используется для замены всех вхождений выбранной подстроки в строке на другую заданную подстроку. Он имеет следующий синтаксис:
- original_string – исходная строка, внутри которой нужно произвести замену.
- old_substring – подстрока, которую нужно заменить.
- new_substring – подстрока, которая будет использоваться вместо old_substring.
- count (необязательный аргумент) – вхождения подстроки, которые нужно заменить. По умолчанию заменятся все вхождения.
Метод replace() возвращает новую строку, полученную в результате замены.
Примеры использования метода replace() в Python
Замена одиночного символа в строке
Рассмотрим пример с заменой одиночного символа в строке при помощи метода replace():
Замена подстроки в строке
Теперь рассмотрим пример, в котором произведём замену подстроки в строке при помощи метода replace():
Удаление одиночного символа из строки
Также метод replace() может использоваться для удаления символов или подстрок в строке. Для этого необходимо заменить их на пустую строку:
Замена элементов списка методом replace()
При помощи метода replace() можно заменять не только символы и подстроки, но и элементы в списках. Для этого необходимо преобразовать список в строку, после чего использовать метод replace():
В приведенном выше примере мы создаем список my_list, преобразуем его в строку str_list с помощью метода join(), заменяем в этой строке подстроку “банан” на подстроку “груша” с помощью метода replace(), а затем преобразуем строку обратно в список методом split().
Заключение
В ходе статьи мы с Вами научились работать с методом replace() в языке программирования Python. Надеюсь Вам понравилась статья, желаю удачи и успехов!