Correspondence between Python built-in functions and Rust

I have confirmed the operation with Rust 1.0

Please note that a good number of APIs remain unstable even in 1.0.

abs

fn abs() {
    println!("abs(-1.5f32)={}", -1.5f32.abs());
    println!("abs(-2i32)={}", -2i32.abs());
}

all

fn all() {
    //range is int type
    (0..10).all(|x| x % 2 == 0);
    //Normal iterator&int type
    [2, 4].iter().all(|&x| x % 2 == 0);
    //It's unpleasant that the types returned by range and iterator are different, so always return a reference.
    //I want you to
}

any

fn any() {
    (0..10).any(|x| x == 9);
    [0, 1].iter().all(|x| *x == 1);
}

ascii Unfortunately the easy way is unstable

fn ascii() {
    // unstable feature
    // println!("unicode escape is [{}]", "Aiueo abcde".escape_unicode());
    // println!("default escape is [{}]", "Aiueo abcde\n\t\r".escape_default());
}

bin

fn bin() {
    //Binary literals can be defined like 0b0011
    let a = 0b1010; // == 10
    let b = format!("0b{:b}", 10);
    println!("{}", b);
}

bytearray, bytes

fn bytearray() {
    // 1
    let x: Vec<char> = vec!['\x20', 'a'];
    // 2
    let mut y = Vec::new();
    write!(&mut y, "abcde");
    // 3
    let z = "Ah".bytes().collect::<Vec<u8>>();
}

chr

fn chr() {
    println!("{:?}", std::char::from_u32(0x61));
}

dict

fn dict() {
   let mut a = std::collections::HashMap::<&str, &str>::new();
   a.insert("a", "A");
}

divmod

fn divmod() {
    let a = 5;
    let (b, c) = (a / 2, a % 2);
    println!("divmod: {}, {}", b, c);
}

enumerate

fn enumerate() {
    // enumerate(start=1)There is no option like
    for (idx, x) in (1..3).enumerate() {
        println!("enumerate: {}, {}", idx, x);
    }
}

filter

fn filter() {
    let x = [1, 2, 3, 4, 5];
    println!("filter: {:?}", x.iter().filter_map(|&x| if x % 2 == 0 {Some(x)} else {None}).collect::<Vec<i32>>());
    //Filter object
    let y = x.iter().filter(|&x| *x % 2 == 0);
}

float

fn float() {
    // from string
   let x = "-1.5e-1".parse::<f32>();
   // from integer
   let y = 100i32 as f32;
   let z = "inf".parse::<f32>();
   println!("float: {:?}, {:?}, {:?}", x, y, z);
}

format

fn format() {
    let x = format!("{}, {}", "hello", "world!");
    println!("{}", x);
}

frozenset, set

fn frozenset() {
    let mut x = std::collections::HashSet::<i32>::new();
    x.insert(0);
    x.insert(1);
    let y = x.clone();  // immutable
    let z: std::collections::HashSet<i32> = [1, 2, 3].iter().map(|&x| x).collect();
}

hash Still unstable

fn hash() {
    // unstable feature
    // println!("hash: {}", std::hash::hash::<_, std::hash::SipHasher>(&0));
}

hex

fn hex() {
    let x = format!("0x{:x}, {}", 0x20, 0x20);
    println!("hex: {}", x);
}

id The only way to find out if they are the same object is to look up the address?

fn id() {
    let x = 1;
    let y = format!("{:p}", &x);  //Get address as a string
    println!("id: x={}", y);
    let z = x;
    println!("id: x is z?: {}", (&z as *const _) == (&x as *const _));
}

input

fn input() {
    print!("Please input any:");
    let mut x = String::new();
    std::io::stdin().read_line(&mut x).ok().expect("Failed");
    println!("input: {}", x);
}

int

fn int() {
    let x: i32 = "123".parse().ok().except("not int");
    assert_eq!(x, 123);
    let y = 123.456f32 as i32;
    assert_eq!(x, y);
}

iter

fn iter() {
    let x = [1, 2];
    let y = x.iter();
}

len

fn len() {
    let x = [1, 2];
    println!("len: {}", x.len());
}

list

fn list() {
    // Fixed size
    let x = [1, 2];
    // Variable size
    let mut y = vec![1, 2];
    y.push(3);
}

map

fn map() {
    let x = [1, 2];
    let y = x.iter().map(|&x| x * 2);
    println!("map: {:?}", y.collect::<Vec<i32>>());
}

max min_max is still unstable

fn max() {
    let x = [1, 3, 2];
    let y = x.iter().max();
    println!("max: {:?}", y);
    println!("max: min_max: {:?}", x.iter().min_max());
    println!("max: number: {}", std::cmp::max(5, 3));
}

min min_max is still unstable

fn min() {
    let x = [1, 3, 2];
    let y = x.iter().min();
    println!("min: {:?}", y);
    // println!("min: min_max: {:?}", x.iter().min_max());
    println!("min: number: {}", std::cmp::min(5, 3));
}

next

fn next() {
    let x = [1, 2, 3];
    let mut y = x.iter();
    println!("next: {:?}", y.next());  //Iterator itself needs to be mutable
    println!("next: {:?}", y.next());
}

oct

fn oct() {
    let x = format!("{:o}", 10);
    println!("oct: {}", x);
}

open

fn open() {
    let x = std::fs::File::open("hoge.txt");
}

ord

fn ord() {
    //Obtained by casting
    let x = 'Ah' as u32;
    println!("ord: 0x{:x}, {}", x, x);
}

pow

fn pow() {
    use std::num::{Int, Float};
    println!("pow: {}", 2.pow(3));
    println!("powf: {}, powi: {}", 2.0f32.powf(3.0f32), 2.0f32.powi(-1));
}

print

fn print() {
    print!("print!");
    println!("println!");
}

range Use range notation. The scattered range by step_by is still unstable

fn _range() {
    println!("range: {:?}", (0..2).collect::<Vec<i32>>());
    // unstable
    // println!("range_step: {:?}", (0..4).step_by(2).collect::<Vec<i32>>());
    // println!("range_step(negative): {:?}", (4..0).step_by(-2).collect::<Vec<i32>>());

reverse

fn reverse() {
    let x = [1, 2];
    for i in x.iter().rev() {println!("reverse: {}", i);}  // reverse iterator
    let mut y = x.clone();
    y.reverse();  //Directly in reverse order
}

round

fn round() {
    //Behavior is different from Python round
    use std::num::Float;
    println!("round 0.5 = {}", 0.5f32.round());
    println!("round -0.5 = {}", -0.5f32.round());
    println!("round 1.5 = {}", 1.5f32.round());
    println!("round -1.5 = {}", -1.5f32.round());
}

slice Expected to be unified into slice notation? Closed sections can no longer be created. What will happen in the future?

fn slice() {
    let x = [1, 2, 3, 4, 5];
    println!("slice of {:?}: {:?}", x, &x[1..3]);
    println!("slice_from of {:?}: {:?}", x, &x[1..]);
    println!("slice_to of {:?}: {:?}", x, &x[..3]);
    println!("full_slice of {:?}: {:?}", x, &x[..]);
}

sorted

fn sorted() {
    // in-place only
    let x = [1, 4, 2, 3];
    let mut y = x.clone();
    y.sort();
    println!("sort: {:?}", y);
}

sum Zubari sum () is still unstable, so fold will be used instead.

fn sum() {
    let x = (1..11).fold(0, |n, x| n + x);
    println!("sum from 1 to 10 = {}", x);
    // unstable
    // println!("sum: {}", (1..11).sum::<i32>());
}

super Rust's super keyword is used to refer to the parent module

use super::child_module;

tuple

fn tuple() {
    let x = (1, "string");
}

type

Is it in std :: intrinsics? Well I do not know

zip

fn zip() {
    let x = [1, 2];
    let y = ["one", "two"];
    //It seems impossible to easily put together three or more elements. Flat yourself_You can do it by writing a function using map
    let z: Vec<(&i32, &&str)> = x.iter().zip(y.iter()).collect();
    println!("{:?}", z);
}


Recommended Posts

Correspondence between Python built-in functions and Rust
Python built-in functions ~ Zip ~
Wrap Python built-in functions
Correspondence between pandas and SQL
Python 3 sorted and comparison functions
Python higher-order functions and comprehensions
Difference between Ruby and Python split
Difference between java and python (memo)
Difference between list () and [] in Python
Difference between == and is in python
Anaconda and Python version correspondence table
Correspondence between RecyclerView and Marker (Kotlin)
Cooperation between python module and API
Difference between python2 series and python3 series dict.keys ()
[Python] Difference between function and method
Python --Difference between exec and eval
[Python] Difference between randrange () and randint ()
[Python] Difference between sorted and sorted (Colaboratory)
Built-in python
Python functions
Communicate between Elixir and Python with gRPC
Differences in authenticity between Python and JavaScript
Differences between Ruby and Python in scope
Conquer 69 Python built-in functions 6th p ~ r
difference between statements (statements) and expressions (expressions) in Python
Differences in syntax between Python and Java
Difference between PHP and Python finally and exit
Difference between @classmethod and @staticmethod in Python
[Python] Difference between class method and static method
[Python3] Switch between Shift_JIS, UTF-8 and ASCII
[Python Iroha] Difference between List and Tuple
[python] Difference between rand and randn output
Differences in multithreading between Python and Jython
Differences between Ruby and Python (basic syntax)
Use Python and MeCab with Azure Functions
Exchange encrypted data between Python and C #
[Python] Case where the execution time differs between the built-in list and deque
Correspondence summary of array operation of ruby and python
Python built-in object
Summary of the differences between PHP and Python
Julia Quick Note [22] Calling Python functions and Python modules
List of frequently used built-in functions and methods
The answer of "1/2" is different between python2 and 3
[python] Difference between variables and self. Variables in class
[Python] Conversion memo between time data and numerical data
About the difference between "==" and "is" in python
Python built-in object
Python hand play (interoperability between CSV and PostgreSQL)
Practice applying functions and global variables in Python
#Python basics (functions)
[Beginner] Python functions
A story about modifying Python and adding functions
Python Easy-to-use functions
Useful Python built-in functions that you use occasionally
Python basics: functions
cv2 functions and data types (OpenCV python bindings)
Python's built-in functions
File write speed comparison experiment between python 2.7.9 and pypy 2.5.0
[Ruby vs Python] Benchmark comparison between Rails and Flask
Control other programs from Python (communication between Python and exe)
Difference between Ruby and Python in terms of variables