12
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PythonからRustに乗り換えたときに使える小技メモ

Last updated at Posted at 2019-10-20

動機

C/C++から出発して主にPythonを使う筆者.現在は,速度と安全性を求めてRustを学習している.
そこで,本稿ではPythonの構文に対応するRustの構文をまとめておく.
また,新たに知り得た段階で随時更新していくこととする.

実行環境

Python = 3.7.4
rustc = 1.38.0

本題

厳密に「1対1対応」なのかは考慮しないものとする.

キャスト

個人的によく使うもの.

a = int('1') # str -> int
b = str(1)   # int -> str
fn main(){
  let num: i32 = "1".parse().unwrap(); // str -> int
  let s: String = num.to_string();     // int -> str
}

enumerate()

enumerate.py
lst = [1, 2, 3, 4]
for idx, v in lst.enumerate():
  print(idx, v)

# OUTPUT:
# 0 1
# 1 2
# 2 3
# 3 4
main.rs
fn main(){
  let vec = vec![1,2,3,4];
  for (idx, v) in vec.iter().enumerate(){
    println!("{} {}", idx, v);
  }
}

zip()

zip.py
vec = [1,2,3,4]
tor = [5,6,7,8]
for v, t in zip(vec, tor):
  print(v, t)

# OUTPUT:
# 1 5
# 2 6
# 3 7
# 4 8
fn main(){
  let vec = vec![1,2,3,4];
  let tor = vec![5,6,7,8];
  for (v, t) in vec.iter().zip(tor.iter()) {
    println!("{} {}", v, t);
  }
}

exit()

import sys

sys.exit(0)
std::process;

fn main() {
  process::exit(0);
}

あくまで安全にプログラムを終了させるだけならreturn;で良いらしい.

fn main() {
  //...(some codes)...
  return;
  //...(some codes)...
}

subprocess

subprocessというcrateもある.

import subprocess as sp

sp.call("ls -al", shell=True)
use std::process::Command;

fn main() {
  let mut child = Command::new("sh").arg("-c")
      .arg("ls -al").spawn().expect("failed to execute process");
  let ecode = child.wait().expect("failed to wait on child")
  assert!(ecode.success());
}

参考

dict

Pythonでいうところの辞書型dictはRustではHashMapとなる.

d = {'a':[1,2,3], 'b':[4,5,6]}
use std::collections::HashMap;

fn main(){
  // d = {'a':[1,2,3], 'b':[4,5,6]}
  let mut map: HashMap<char, Vec<usize>> = HashMap::new();
  map.insert('a', vec![1,2,3]);
  map.insert('b', vec![4,5,6]);
}

Keyがあるかどうかの確認

print('a' in d) # -> True
println!("{:?}", map.contains_key(&'a')); // -> true

dictの中身のlistの要素を削除

詳しくは別の記事を参照

# まずはIndexを取得する
index = d['a'].index(1)
# 要素の削除
del d['a'][index]
// まずはIndexを取得する
let index = map[&'a'].iter().position(|x| *x == 1).unwrap();
// HashMapの要素に対するIndexMutは無くなってしまったので代わりにget_mut()を使う
map.get_mut(&'a').unwrap().remove(index);

sum

lst = [1, 2, 3, 4]
print(lst.sum()) #=> 10
let lst = vec![1,2,3,4];
let lst_sum: u64 = lst.iter().sum();
println!("{}", lst_sum); #=> 10
12
8
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?