Oktatás
* Programozás 1 + feladatsor + GitHub oldal
* Szkriptnyelvek + feladatsor + quick link
Teaching
* Programming 1 (BI) ◇ exercises ◇ quick link
teaching assets
Félévek
* 2024/25/2 * archívum
Linkek
* kalendárium - munkaszüneti napok '20 * tételsorok * jegyzetek * szakdolgozat / PhD * ösztöndíjak * certificates * C lang. * C++ * C# * Clojure * D lang. * Java * Nim * Scala
[ edit | logout ] [ sandbox | passwd ]
|
See also std.algorithm.
(1) remove an element
|
def main():
# delete element at a given INDEX position
li = [8, 5, 1, 3, 9]
del li[2]
print(li) # [8, 5, 3, 9]
# ----------
# remove the FIRST occurrence of an element
data = [8, 5, 1, 3, 9, 5]
data.remove(5)
print(data) # [8, 1, 3, 9, 5]
|
import std.stdio;
import std.algorithm; // remove()
void main()
{
// delete element at a given INDEX position
int[] li = [8, 5, 1, 3, 9];
li = li.remove(2); // !!! assign back !!!
writeln(li); // [8, 5, 3, 9]
// ----------
// this one removes ALL occurrences
int[] data = [8, 5, 1, 3, 9, 5];
data = data.remove!(x => x == 5);
writeln(data); // [8, 1, 3, 9]
}
|
Important! Write li = li.remove(2); , i.e. the result of the remove operation must be assigned back to the same array variable. Why? Because the length of the dynamic array changes and li is a fat pointer that holds two values: a pointer and the number of elements in the dynamic array. And the number of elements changes, thus li must be updated.
In Python, if you want to remove ALL the occurrences, you can use a list comprehension:
def main():
data = [8, 5, 1, 3, 9, 5]
elem = 5
data = [x for x in data if x != elem]
print(data) # [8, 1, 3, 9]
In D, if you want to remove just the first occurrence of an element:
(2) remove just the FIRST occurrence
|
|
import std.stdio;
import std.algorithm; // countUntil()
/// Removes the first occurrence of `value` from `arr` (like Python's list.remove())
/// Returns true if removed, false if not found.
bool removeFirst(T)(ref T[] arr, T value)
{
auto idx = arr.countUntil(value);
if (idx == -1)
{
return false;
}
// else
arr = arr.remove(idx);
return true;
}
void main()
{
int[] data = [8, 5, 1, 3, 9, 5];
data.removeFirst(5); // removes first 5
writeln(data); // [8, 1, 3, 9, 5]
}
|
|
Blogjaim, hobbi projektjeim
* The Ubuntu Incident * Python Adventures * @GitHub * heroku * extra * haladó Python * YouTube listák
Debrecen | la France
[ edit ]
|