Un résumé des opérations typiques de Array en Ruby et Hash (Dictionnaire) en Python.
Ceci est un article pour Rubyist (Pythonista) qui vient de commencer à apprendre Python (Ruby).
h = {"a" => 1, "b" => 2, "c" => 3}
h2 = {a: 1, b: 2, c: 3} #Quand le symbole est la clé
d = {'a': 1, 'b': 2, 'c': 3}
h['c'] #=> 3
h['d'] #=> nil
d['c'] #=> 3
d['d'] #=>Une exception KeyError se produit
size
h.size #=> 3
len( d ) #=> 3
each
Boucle autour de l'élément
h.each do |key,val|
puts key,val
end
for k,v in d.items():
print(k,v)
keys, values
Obtenez une liste de clés et de valeurs
h.keys #=> ["a", "b", "c"]
h.values #=> [1, 2, 3]
list ()
si vous voulez une liste.keys = d.keys() #=> dict_keys(['b', 'a', 'c'])
values = d.values() #=> dict_values([2, 1, 3])
d['d'] = 4
keys #=> dict_keys(['b', 'd', 'a', 'c'])
values #=> dict_values([2, 4, 1, 3])
list(keys) #=> ['b', 'd', 'a', 'c']
a = [1,2,3,4]
a.map {|x| [x,x+3] }.to_h #=> {1=>4, 2=>5, 3=>6, 4=>7}
a = [1,2,3,4]
{ i:i+3 for i in a } #=> {1: 4, 2: 5, 3: 6, 4: 7}
Hash []
h = {"a" => 1, "b" => 2, "c" => 3}
h.map {|k,v| [k.upcase, -v] } #=> [["A", -1], ["B", -2], ["C", -3]]
h.map {|k,v| [k.upcase, -v] }.to_h #=> {"A"=>-1, "B"=>-2, "C"=>-3}
d = {'a': 1, 'b': 2, 'c': 3}
{ k.upper():-v for k,v in d.items() } #=> {'A': -1, 'B': -2, 'C': -3}
has_key?
h = {"a" => 1, "b" => 2, "c" => 3}
h.has_key?("a") #=> true
h.has_key?("d") #=> false
d.has_key ('a')
jusqu'à python2.d = {'a': 1, 'b': 2, 'c': 3}
'a' in d #=> True
'd' in d #=> False
merge
Hash # merge
. Méthode non destructive. La méthode destructrice est «fusionner!»h1 = {"a" => 1, "b" => 2, "c" => 3}
h2 = {"d" => 4, "e" => 5, "f" => 6}
h1.merge(h2)
# => {"a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5, "f"=>6}
d1 = {"a": 1, "b": 2, "c": 3}
d2 = {"d": 4, "e": 5, "f": 6}
d1.update(d2)
d1
#=> {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
delete
h = {"a" => 1, "b" => 2, "c" => 3}
h.delete('a') #=> 1
h #=> {"b"=>2, "c"=>3}
d = {"a": 1, "b": 2, "c": 3}
d.pop('a') #=> 1
d #=> {'b': 2, 'c': 3}
Cas d'utilisation d'un tableau associatif lors de la prise d'un histogramme
chars = ["a", "b", "b", "c", "c", "c"]
h = Hash.new(0)
chars.each {|c| h[c] += 1 } #Compter le nombre de caractères
h #=> {"a"=>1, "b"=>2, "c"=>3}
default_dict
chars = ["a", "b", "b", "c", "c", "c"]
d = {}
for c in chars:
d[c] = d.get(c,0) + 1 #Obtient s'il y a une valeur, renvoie 0 sinon
d #=> {'a': 1, 'b': 2, 'c': 3}
from collections import defaultdict
chars = ["a", "b", "b", "c", "c", "c"]
d = defaultdict( lambda: 0 )
for c in chars:
d[c] += 1
d
# => defaultdict(<function __main__.<lambda>>, {'a': 1, 'b': 2, 'c': 3})
Hash.new ([])
est un bogue
words = ["a1", "b1", "b2", "c1", "c2", "c3"]
h = Hash.new {|hash,key| hash[key] = [] }
words.each {|w| h[ w[0] ] << w }
h
# => {"a"=>["a1"], "b"=>["b1", "b2"], "c"=>["c1", "c2", "c3"]}
words = ["a1", "b1", "b2", "c1", "c2", "c3"]
d = defaultdict( list )
for w in words:
key = w[0]
d[key].append(w)
d
#=> defaultdict(list, {'a': ['a1'], 'b': ['b1', 'b2'], 'c': ['c1', 'c2', 'c3']})
Recommended Posts