Python list comprehension is really simple:
>>> l = [x for x in range(1, 10) if x % 2 == 0] >>> [2, 4, 6, 8]
Does Rust have an equivalent syntax like:
let vector = vec![x for x in (1..10) if x % 2 == 0] // [2, 4, 6, 8]
List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list. Example: Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name.
PythonServer Side ProgrammingProgramming. We can create new sequences using a given python sequence. This is called comprehension. It basically a way of writing a concise code block to generate a sequence which can be a list, dictionary, set or a generator by using another sequence.
Python is famous for allowing you to write code that's elegant, easy to write, and almost as easy to read as plain English. One of the language's most distinctive features is the list comprehension, which you can use to create powerful functionality within a single line of code.
For loops are faster than list comprehensions to run functions.
You can just use iterators:
fn main() { let v1 = (0u32..9).filter(|x| x % 2 == 0).map(|x| x.pow(2)).collect::<Vec<_>>(); let v2 = (1..10).filter(|x| x % 2 == 0).collect::<Vec<u32>>(); println!("{:?}", v1); // [0, 4, 16, 36, 64] println!("{:?}", v2); // [2, 4, 6, 8] }
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