Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Rust have an equivalent to Python's list comprehension syntax?

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] 
like image 412
Darkaird Avatar asked Jul 24 '17 14:07

Darkaird


People also ask

What is the syntax of list comprehension in Python?

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.

What is comprehension equivalent in Python?

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.

Does Python have list comprehension?

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.

What is faster than list comprehension Python?

For loops are faster than list comprehensions to run functions.


1 Answers

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] } 
like image 99
ljedrz Avatar answered Sep 19 '22 17:09

ljedrz