Correspondence summary of array operation of ruby and python

Overview

A summary of typical operations of Ruby Array and Python list.

This is an article for Rubyist (Pythonista) who has just started learning Python (Ruby).

Reference: Click here for C ++ version Ruby-C ++ Array operation support summary

Prerequisites

Reference information

Method

size

[1,2,3].size   #=> 3
len( [1,2,3] )   #=> 3

each

Loop around the element

[1,2,3,4,5].each do |x|
  puts 2*x    #=> 2,4,6,8,10
end
for x in [1,2,3,4,5]:
    print(2*x)

each_with_index

Turn the loop with index

[5,4,3,2,1].each_with_index do |x,idx|
  print "#{idx}:#{x}, "
end
# => 0:5, 1:4, 2:3, 3:2, 4:1,
for idx,x in enumerate( [5,4,3,2,1] ):
    print("{0}:{1}, ".format(idx,x), end="")

Joining arrays

[1,2,3] + [4,5]     # [1,2,3,4,5]
[1,2,3] + [4,5]

push (<<)

Add element at the end

a = [1,2]
a << 3
# a => [1,2,3]
a = [1,2]
a.append(3)
# a => [1,2,3]

map

[1,2,3].map {|x| 2*x }  #=> [2,4,6]
[ 2*x for x in [1,2,3] ]                 # => [2,4,6]
list( map( lambda x: 2*x, [1,2,3] ) )    # => [2,4,6]

find

[7,8,9,10,11].find {|x| x%5 == 0 }  #=> 10
[ x for x in [7,8,9,10,11] if x % 5 == 0 ][0]   #=> 10

--Addition: http://stackoverflow.com/questions/9868653/find-first-list-item-that-matches-criteria --The second argument is the default value

next((x for x in [7,8,9,10,11] if x % 5 == 0), None)

find_all

[1,2,3,4,5].find_all {|x| x>3 }  #=> [4,5]
[ x for x in [1,2,3,4,5] if x > 3]     #=> [4,5]
list( filter( lambda x: x>3, [1,2,3,4,5] ) )    #=> [4,5]

sort

[4,1,3,2,5].sort  #=> [1,2,3,4,5]
sorted( [4,1,3,2,5] )   #=> [1,2,3,4,5]

sort_by

[4,1,2,3,5].sort_by {|x| (3-x).abs }  #=> [3,4,2,1,5]
sorted( [4,1,3,2,5], key= lambda x: abs(3-x) )

index

[5,1,4,2,3].index(2)  #=> 3
[5,1,4,2,3].index(2)  #=> 3

all?

[2,4,6,8].all? {|x| x % 2 == 0 }  #=> true
[2,4,6,9].all? {|x| x % 2 == 0 }  #=> false
all( x%2==0 for x in [2,4,6,8] )   #=> True
all( x%2==0 for x in [2,4,6,9] )   #=> False

sum

[1,3,5].inject(:+)   #=> 9
sum( [1,3,5] )

inject (reduce)

[1,2,3,4,5].inject(1) {|acc,x| acc*x }   #=> 120
[1,2,3,4,5].inject("") {|acc,x| acc + (x%2==0?'e':'o') }   #=> oeoeo
import functools
functools.reduce( lambda acc,x: acc*x, [1,2,3,4,5], 1 )
functools.reduce( lambda acc,x: acc+("e" if x%2==0 else "o") , [1,2,3,4,5], "" )

uniq

[5,1,1,2,3,5,5].uniq  #=> [5,1,2,3]
list( set( [5,1,1,2,3,5,5] ) )

li_uniq = []
for x in [5,1,1,2,3,5,5]:
  if x not in li_uniq:
    li_uniq.append(x)
li_uniq    #=> [5,1,2,3]

uniq {block}

[4,5,1,2,3,4,5].uniq {|x| x % 3 }   #=> [4,5,3]
li_uniq = []
set_uniq = set()
for x in [4,5,1,2,3,4,5]:
  if x % 3 not in set_uniq:
    li_uniq.append(x)
    set_uniq.add(x%3)
li_uniq                    #=> [4,5,3]

join

[1,5,3,2].join(":")  #=> "1:5:3:2"
":".join(map(str, [1,5,3,2]))

reverse

[1,2,3].reverse  #=> [3,2,1]
a = [1,2,3]
a.reverse!
a                #=> [3,2,1]
list( reversed([1,2,3]) )

a = [1,2,3]
a.reverse()
a                #=> [3,2,1]

group_by

["cat","bat","bear","camel","alpaca"].group_by {|x| x[0]}
# {"c"=>["cat", "camel"], "b"=>["bat", "bear"], "a"=>["alpaca"]}
d = {}
for x in ["cat","bat","bear","camel","alpaca"]:
    key = x[0]
    if key not in d:
        d[key] = []
    d[key].append(x)
d        # => {'c': ['cat', 'camel'], 'a': ['alpaca'], 'b': ['bat', 'bear']}

shuffle

[1,2,3,4,5,6,7].shuffle   #=> [2, 6, 4, 7, 5, 3, 1]
import random
a = [1,2,3,4,5,6,7]
random.shuffle(a)
a                       #=> [4, 5, 6, 2, 7, 1, 3]

Recommended Posts

Correspondence summary of array operation of ruby and python
Summary of Hash (Dictionary) operation support for Ruby and Python
Summary of Python indexes and slices
[Python] Summary of array generation (initialization) time! !! !!
[Python] Operation of enumerate
Summary of the differences between PHP and Python
Specifying the range of ruby and python arrays
Ruby, Python and map
Installation of Python3 and Flask [Environment construction summary]
Python and Ruby split
Python directory operation summary
Summary of Python arguments
I / O related summary of python and fortran
About shallow and deep copies of Python / Ruby
[python] Array slice operation
Comparison of Python and Ruby (Environment / Grammar / Literal)
Basic operation of Python Pandas Series and Dataframe (1)
Python --Explanation and usage summary of the top 24 packages
[Python] Type Error: Summary of error causes and remedies for'None Type'
Difference between Ruby and Python in terms of variables
Summary of date processing in Python (datetime and dateutil)
Comparison of CoffeeScript with JavaScript, Python and Ruby grammar
Version control of Node, Ruby and Python with anyenv
Summary of python file operations
Summary of Python3 list operations
Python on Ruby and angry Ruby on Python
Python and ruby slice memo
Standard input / summary / python, ruby
Ruby and Python syntax ~ branch ~
Source installation and installation of Python
[python] Summary of how to retrieve lists and dictionary elements
[Python] Summary of how to use split and join functions
Summary of Differences Between Ruby on Rails and Django ~ Basics ~
Environment construction of python and opencv
Difference between Ruby and Python split
The story of Python and the story of NaN
[Python] Operation memo of pandas DataFrame
Installation of SciPy and matplotlib (Python)
Scraping with Node, Ruby and Python
Anaconda and Python version correspondence table
A brief summary of Python collections
[python] week1-3: Number type and operation
This and that of python properties
Compare Python and JavaScript array loops
Coexistence of Python2 and 3 with CircleCI (1.0)
Reputation of Python books and reference books
[OpenCV; Python] Summary of findcontours function
I compared the speed of Hash with Topaz, Ruby and Python
Solving with Ruby, Python and numpy AtCoder ABC054 B Matrix operation
Summary of differences between Python and PHP (comparison table of main items)
Installation of Visual studio code and installation of python
[Python] Summary of how to use pandas
Python Summary
Differences between Ruby and Python in scope
Python + Selenium Frequently used operation method summary
Eating and comparing programming languages: Python and Ruby
Extraction of tweet.js (json.loads and eval) (Python)
Python> link> 2D array initialization and assignment
Summary of various for statements in Python
Connect a lot of Python or and and
Python summary