What's the prettiest way to compare one value against multiple values?
Don't try to be too sneaky, especially when it needlessly affects performance.
If you really have a whole heap of comparisons to do, just format it nicely.
if (foobar === foo ||
foobar === bar ||
foobar === baz ||
foobar === pew) {
//do something
}
Concise way to compare against multiple values
With a regex:
if (/^(something|nothing|anything|everything)$/.exec('jesus')) alert('Who cares?');
Or the opposite:
/^(something|nothing|anything|everything)$/.exec('jesus')||alert('Who cares?');
[Update] Even shorter ;-)
if (/^(some|no|any|every)thing$/.exec('jesus')) alert('Who cares?');
How to test multiple variables for equality against a single value?
You misunderstand how boolean expressions work; they don't work like an English sentence and guess that you are talking about the same comparison for all names here. You are looking for:
if x == 1 or y == 1 or z == 1:
x
and y
are otherwise evaluated on their own (False
if 0
, True
otherwise).
You can shorten that using a containment test against a tuple:
if 1 in (x, y, z):
or better still:
if 1 in {x, y, z}:
using a set
to take advantage of the constant-cost membership test (i.e. in
takes a fixed amount of time whatever the left-hand operand is).
Explanation
When you use or
, python sees each side of the operator as separate expressions. The expression x or y == 1
is treated as first a boolean test for x
, then if that is False, the expression y == 1
is tested.
This is due to operator precedence. The or
operator has a lower precedence than the ==
test, so the latter is evaluated first.
However, even if this were not the case, and the expression x or y or z == 1
was actually interpreted as (x or y or z) == 1
instead, this would still not do what you expect it to do.
x or y or z
would evaluate to the first argument that is 'truthy', e.g. not False
, numeric 0 or empty (see boolean expressions for details on what Python considers false in a boolean context).
So for the values x = 2; y = 1; z = 0
, x or y or z
would resolve to 2
, because that is the first true-like value in the arguments. Then 2 == 1
would be False
, even though y == 1
would be True
.
The same would apply to the inverse; testing multiple values against a single variable; x == 1 or 2 or 3
would fail for the same reasons. Use x == 1 or x == 2 or x == 3
or x in {1, 2, 3}
.
Concise way to compare a variable against multiple values
You can use in
operator:
for i in range(10):
if i in (3, 5) or math.sqrt(i) in (3, 5):
numbers.append(i)
or in case you expect each of the calculations to be in the same group of results, you can use any()
results = [1, 2, ..., too long list for single line]
expected = (3, 5)
if any([result in expected for result in results]):
print("Found!")
Just a minor nitpick, sqrt
will most likely return a float
sooner or later and this approach will be silly in the future, therefore math.isclose()
or others will help you not to encounter float "bugs" such as:
2.99999999999999 in (3, 5) # False
which will cause your condition to fail.
Most efficient way to compare a variable to multiple values?
If the values you want to check are sufficiently small, you could create a bit mask of the values that you seek and then check for that bit to be set.
Suppose, you care about a couple of groups.
static const unsigned values_group_1 = (1 << 1) | (1 << 2) | (1 << 3);
static const unsigned values_group_2 = (1 << 4) | (1 << 5) | (1 << 6);
static const unsigned values_group_3 = (1 << 7) | (1 << 8) | (1 << 9);
if ((1 << value_to_check) & values_group_1) {
// You found a match for group 1
}
if ((1 << value_to_check) & values_group_2) {
// You found a match for group 2
}
if ((1 << value_to_check) & values_group_3) {
// You found a match for group 3
}
This approach works best for values that don't exceed the natural size your CPU likes to work with. This would typically be 64 in modern times, but may vary depending upon the specifics of your environment.
Compare one String with multiple values in one expression
I found the better solution. This can be achieved through RegEx:
if (str.matches("val1|val2|val3")) {
// remaining code
}
For case insensitive matching:
if (str.matches("(?i)val1|val2|val3")) {
// remaining code
}
How to compare a value to several other values in one line in Kotlin
I think the simplest way is with the in
operator:
a in listOf(b, c)
you can include as many items as you want inside the list.
Compare multiple values against the same variable
Use indexOf
with array of values
var valArr = ["kivi","apples","lychee","banana.C","mangos"];
if(valArr.indexOf(val) > -1){
.......
}
Related Topics
"Uncaught Syntaxerror: Cannot Use Import Statement Outside a Module" When Importing Ecmascript 6
How to Enable Cors in Angularjs
Xml Parsing of a Variable String in JavaScript
Combination of Async Function + Await + Settimeout
Jquery .Live() VS .On() Method For Adding a Click Event After Loading Dynamic Html
Set a Default Parameter Value For a JavaScript Function
How to Iterate Over a JavaScript Object
Pass Correct "This" Context to Settimeout Callback
What's the Prettiest Way to Compare One Value Against Multiple Values
Define a Global Variable in a JavaScript Function
How to "Properly" Create a Custom Object in JavaScript
Passing Data to a Bootstrap Modal
How to Create an Array Containing 1...N
How to Loop Through a Plain JavaScript Object With the Objects as Members
Async Function Returning Promise, Instead of Value
Test For Existence of Nested JavaScript Object Key
How to Attach Events to Dynamic HTML Elements With Jquery
How to Find Event Listeners on a Dom Node in JavaScript or in Debugging