I'm translating some of my Python code to Scala, and I was wondering if there's an equivalent to Python's list-comprehension:
[x for x in list if x!=somevalue]
Essentially I'm trying to remove certain elements from the list if it matches.
Scala offers a lightweight notation for expressing sequence comprehensions. Comprehensions have the form for (enumerators) yield e , where enumerators refers to a semicolon-separated list of enumerators. An enumerator is either a generator which introduces new variables, or it is a filter.
For loops are faster than list comprehensions to run functions.
Actually, list comprehension is much clearer and faster than filter+lambda, but you can use whichever you find easier. The first thing is the function call overhead: as soon as you use a Python function (whether created by def or lambda) it is likely that the filter will be slower than the list comprehension.
The difference between Lambda and List Comprehension. List Comprehension is used to create lists, Lambda is function that can process like other functions and thus return values or lists.
The closest analogue to a Python list comprehension would be
for (x <- list if x != somevalue) yield x
But since you're what you're doing is filtering, you might as well just use the filter
method
list.filter(_ != somevalue)
or
list.filterNot(_ == somevalue)
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