JavaScript version:
https://dev.to/akuad/alternative-of-for-in-javascript-3p71/edit
Introduction
There are some cases of processing elements in list. Basically solution is process with for.
Actually, there are other solutions without using for. Them can reduce code and keep code in simple.
Note: In some cases, for can be the best solution.
Tutorial: lambda expression
These codes will be take same behavior.
def func(e):
return e*2
lambda e: e*2
By using lambda:, you can omit def, function name and return.
Make an Array what elements processed
E.g. multiplex x2
in_list = [1, 2, 3, 4]
out_list = []
for e in in_list:
out_list.append(e * 2)
# out_list: [2, 4, 6, 8]
in_list = [1, 2, 3, 4]
out_list = map(lambda e: e*2, in_list)
# out_list: [2, 4, 6, 8]
Reference: map()
If you good for list comprehensions, it can be more few code.
in_list = [1, 2, 3, 4]
out_list = [e*2 for e in in_list]
Extract elements what match to a condition
E.g. Extract even numbers from Array
array = [1, 2, 3, 4]
array_even = []
for e in array:
if e % 2 == 0:
array_even.append(e)
# array_even: [2, 4]
array = [1, 2, 3, 4]
array_even = filter(lambda e: (e % 2) == 0, array)
# array_even: [2, 4]
Reference: filter()
Check is a value in Array
E.g. Check is input string day-name
in_text = "mon"
day_names = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"]
is_input_true = False
for e in day_names:
if in_text == e:
is_input_true = True
break
# is_input_true: True
in_text = "mon"
day_names = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"]
is_input_true = in_text in day_names
# is_input_true: true
Reference: Membership test operations
Conclusion
Sometimes let’s see document (language reference, command help and so on).
You can find good functions, methods or options.
Top comments (0)