I have a list of tuples, say,
[{x, a, y}, {x, b, y}].
Is there a built-in function (or can I use a combination of BIFs) to delete all tuples matching {x, _, y}
, as in match and delete based on the first and third term in the tuples, ignoring the second?
Use the del statement to remove a tuple from a list of tuples, e.g. del list_of_tuples[0] . The del statement can be used to remove a tuple from a list by its index, and can also be used to remove slices from a list of tuples.
Note: You cannot remove items in a tuple.
Tuple Matching in Python is a method of grouping the tuples by matching the second element in the tuples. It is achieved by using a dictionary by checking the second element in each tuple in python programming. However, we can make new tuples by taking portions of existing tuples.
The remove() method removes the first matching element (which is passed as an argument) from the list. The pop() method removes an element at a given index, and will also return the removed item. You can also use the del keyword in Python to remove an element or slice from a list.
The lists:filter/1 function matches your need, e.g.
Ls = [{x,a,y}, {a,b,c}],
F = fun ({x,_,y}) -> false ; (_) -> true end,
lists:filter(F, Ls).
You can also use list comprehensions, which is like a combination of lists:map/2 and lists:filter/2.
[L || L <- Ls, F(L)]
If your predicate was the opposite, in that you only wanted those matching {x,_,y} you could write it as following, because the generator will filter out those not matching the pattern.
[L || {x,_,y}=L <- Ls]
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