Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching and deleting items in list of tuples

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?

like image 380
Sappe Avatar asked Apr 06 '10 22:04

Sappe


People also ask

How do I delete a tuple from a list?

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.

Can we delete items in a tuple?

Note: You cannot remove items in a tuple.

What is tuple matching?

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.

How do I remove a matching element from a list in Python?

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.


1 Answers

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]
like image 181
Christian Avatar answered Oct 04 '22 07:10

Christian