2

Given an array like:

5-element Array{String,1}:
 "Computer science"
 "Artificial intelligence"
 "Machine learning"
 "Algorithm"
 "Mathematics"

How does one filter it by multiple conditions in Julia? For example, I want to obtain all the values that are not "Computer science" or "Artificial intelligence", hence, I want to obtain:

3-element Array{String,1}:
 "Machine learning"
 "Algorithm"
 "Mathematics"

1 Answer 1

4

Maybe something like this?

julia> x = ["Computer science", "Artificial intelligence", "Machine learning", "Algorithm", "Mathematics"]
5-element Array{String,1}:
 "Computer science"
 "Artificial intelligence"
 "Machine learning"
 "Algorithm"
 "Mathematics"

# Note the double parentheses, in order to build the
# ("Computer science", "Artificial intelligence") tuple
#
# It would also be possible (but probably less efficient) to put
# those values in a vector
julia> filter(!in(("Computer science", "Artificial intelligence")), x)
3-element Array{String,1}:
 "Machine learning"
 "Algorithm"
 "Mathematics"

Edit: as mentioned in comments, if the list of values to filter out is longer, it might be more efficient to build a Set instead of a Tuple:

julia> filter(!in(Set(("Computer science", "Artificial intelligence"))), x)
3-element Array{String,1}:
 "Machine learning"
 "Algorithm"
 "Mathematics"
Sign up to request clarification or add additional context in comments.

2 Comments

It should be noted that if the list of values for filtering is longer than just few elements they should be put into a Set that has O(ln(n)) search time rather than O(n) in case of a tuple or vector. For short filtering lists the proposed approach will be indeed fastest.
Good idea @PrzemyslawSzufel! I edited my answer to reflect your comment, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.