How do I replace elements in a list
with another?
For example I want all two
to become one
?
You can replace items in a Python list using list indexing, a list comprehension, or a for loop. If you want to replace one value in a list, the indexing syntax is most appropriate.
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.
Replace a specific string in a list. If you want to replace the string of elements of a list, use the string method replace() for each element with the list comprehension. If there is no string to be replaced, applying replace() will not change it, so you don't need to select an element with if condition .
Python String replace() Method The replace() method replaces a specified phrase with another specified phrase. Note: All occurrences of the specified phrase will be replaced, if nothing else is specified.
You can use:
Collections.replaceAll(list, "two", "one");
From the documentation:
Replaces all occurrences of one specified value in a list with another. More formally, replaces with
newVal
each elemente
in list such that(oldVal==null ? e==null : oldVal.equals(e))
. (This method has no effect on the size of the list.)
The method also return a boolean
to indicate whether or not any replacement was actually made.
java.util.Collections
has many more static
utility methods that you can use on List
(e.g. sort
, binarySearch
, shuffle
, etc).
The following shows how Collections.replaceAll
works; it also shows that you can replace to/from null
as well:
List<String> list = Arrays.asList(
"one", "two", "three", null, "two", null, "five"
);
System.out.println(list);
// [one, two, three, null, two, null, five]
Collections.replaceAll(list, "two", "one");
System.out.println(list);
// [one, one, three, null, one, null, five]
Collections.replaceAll(list, "five", null);
System.out.println(list);
// [one, one, three, null, one, null, null]
Collections.replaceAll(list, null, "none");
System.out.println(list);
// [one, one, three, none, one, none, none]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With