- 浏览: 863409 次
- 性别:
- 来自: 上海
文章分类
最新评论
-
yukang1:
蚂蚁lovejing 写道我也出现与楼上相同的问题。查了一些资 ...
Spring中实现文件上传 -
史玉凤:
必须用ie浏览器
javascript获取客户端网卡MAC地址和IP地址和计算机名 -
蚂蚁lovejing:
我也出现与楼上相同的问题。查了一些资料,描述的跟楼主的博文差不 ...
Spring中实现文件上传 -
温柔一刀:
djlijian 写道最近也在研究redis,如何在项目中使用 ...
Redis 常见的性能问题和解决方法 -
djlijian:
最近也在研究redis,如何在项目中使用呢?感觉网上的资料太少 ...
Redis 常见的性能问题和解决方法
Hashes are known in some circles as associative arrays, dictionaries, and various other names. Perl and Java programmers in particular will be familiar with this data structure.
Think of an array as an entity that creates an association between an index x and a data item y. A hash creates a similar association with at least two exceptions. First, for an array, x is always an integer; for a hash, it need not be. Second, an array is an ordered data structure; a hash typically has no ordering.
A hash key can be of any arbitrary type. As a side effect, this makes a hash a nonsequential data structure. In an array, we know that element 4 follows element 3; but in a hash, the key may be of a type that does not define a real predecessor or successor. For this reason (and others), there is no notion in Ruby of the pairs in a hash being in any particular order.
You may think of a hash as an array with a specialized index, or as a database "synonym table" with two fields stored in memory. Regardless of how you perceive it, a hash is a powerful and useful programming construct.
8.2.1. Creating a New Hash
As with Array, the special class method [] is used to create a hash. The data items listed in the brackets are used to form the mapping of the hash.
Six ways of calling this method are shown here. (Hashes a1 through c2 will all be populated identically.)
a1 = Hash.[]("flat",3,"curved",2) a2 = Hash.[]("flat"=>3,"curved"=>2) b1 = Hash["flat",3,"curved",2] b2 = Hash["flat"=>3,"curved"=>2] c1 = {"flat",3,"curved",2} c2 = {"flat"=>3,"curved"=>2} # For a1, b1, and c1: There must be # an even number of elements.
There is also a class method called new that can take a parameter specifying a default value. Note that this default value is not actually part of the hash; it is simply a value returned in place of nil.
d = Hash.new # Create an empty hash e = Hash.new(99) # Create an empty hash f = Hash.new("a"=>3) # Create an empty hash e["angled"] # 99 e.inspect # {} f["b"] # {"a"=>3} (default value is # actually a hash itself) f.inspect # {}
8.2.2. Specifying a Default Value for a Hash
The default value of a hash is an object referenced in place of nil in the case of a missing key. This is useful if you plan to use methods with the hash value that are not defined for nil. It can be assigned upon creation of the hash or at a later time using the default= method.
All missing keys point to the same default value object, so changing the default value has a side effect.
a = Hash.new("missing") # default value object is "missing" a["hello"] # "missing" a.default="nothing" a["hello"] # "nothing" a["good"] << "bye" # "nothingbye" a.default # "nothingbye"
There is also a special instance method fetch that raises an IndexError exception if the key does not exist in the Hash object. It takes a second parameter that serves as a default value. Also fetch optionally accepts a block to produce a default value in case the key is not found. This is in contrast to default because the block allows each missing key to have its own default.
a = {"flat",3,"curved",2,"angled",5} a.fetch("pointed") # IndexError a.fetch("curved","na") # 2 a.fetch("x","na") # "na" a.fetch("flat") {|x| x.upcase} # 3 a.fetch("pointed") {|x| x.upcase} # "POINTED"
8.2.3. Accessing and Adding Key-Value Pairs
Hash has class methods [] and []= just as Array has; they are used much the same way, except that they accept only one parameter. The parameter can be any object, not just a string (although string objects are commonly used).
a = {} a["flat"] = 3 # {"flat"=>3} a.[]=("curved",2) # {"flat"=>3,"curved"=>2} a.store("angled",5) # {"flat"=>3,"curved"=>2,"angled"=>5}
The method store is simply an alias for the []= method, both of which take two arguments as shown in the preceding example.
The method fetch is similar to the [] method, except that it raises an IndexError for missing keys. It also has an optional second argument (or alternatively a code block) for dealing with default values (see section 8.2.2, "Specifying a Default Value for a Hash" earlier in this chapter).
a["flat"] # 3 a.[]("flat") # 3 a.fetch("flat") # 3 a["bent"] # nil
Suppose that we are not sure whether the Hash object exists, and we want to avoid clearing an existing hash. The obvious way is to check whether the hash is defined:
unless defined? a a={} end a["flat"] = 3
Another way to do this is as follows:
a ||= {} a["flat"] = 3 # Or even: (a ||= {})["flat"] = 3
The same problem can be applied to individual keys, where you want to assign a value only if the key does not exist:
a=Hash.new(99) a[2] # 99 a # {} a[2] ||= 5 # 99 a # {} b=Hash.new b # {} b[2] # nil b[2] ||= 5 # 5 b # {2=>5}
Note that nil may be used as either a key or an associated value:
b={} b[2] # nil b[3]=nil b # {3=>nil} b[2].nil? # true b[3].nil? # true b[nil]=5 b # {3=>nil,nil=>5} b[nil] # 5 b[b[3]] # 5
8.2.4. Deleting Key-Value Pairs
Key-value pairs of a Hash object can be deleted using clear, delete, delete_if, reject, reject!, and shift.
Use clear to remove all key-value pairs. This is essentially the same as assigning a new empty hash but marginally faster.
Use shift to remove an unspecified key-value pair. This method returns the pair as a two-element array, or nil if no keys are left.
a = {1=>2, 3=>4} b = a.shift # [1,2] # a is now {3=>4}
Use delete to remove a specific key-value pair. It accepts a key and returns the value associated with the key removed (if found). If not found, the default value is returned. It also accepts a block to produce a unique default value rather than just a reused object reference.
a = {1=>1, 2=>4, 3=>9, 4=>16} a.delete(3) # 9 # a is now {1=>1, 2=>4, 4=>16} a.delete(5) # nil in this case a.delete(6) { "not found" } # "not found"
Use delete_if, reject, or reject! in conjunction with the required block to delete all keys for which the block evaluates to true. The method reject uses a copy of the hash, and reject! returns nil if no changes were made.
8.2.5. Iterating Over a Hash
The Hash class has the standard iterator each as is to be expected. It also has each_key, each_pair, and each_value. (each_pair is an alias for each.)
{"a"=>3,"b"=>2}.each do |key, val| print val, " from ", key, "; " # 3 from a; 2 from b; end
The other two provide only one or the other of key or value to the block:
{"a"=>3,"b"=>2}.each_key do |key| print "key = #{key};" # Prints: key = a; key = b; end {"a"=>3,"b"=>2}.each_value do |value| print "val = #{value};" # Prints: val = 3; val = 2; end
8.2.6. Inverting a Hash
Inverting a hash in Ruby is trivial with the invert method:
a = {"fred"=>"555-1122","jane"=>"555-7779"} b = a.invert b["555-7779"] # "jane"
Since hashes have unique keys, there is potential for data loss when doing this: Duplicate associated values will be converted to a unique key using only one of the associated keys as its value. There is no predictable way to tell which one will be used.
8.2.7. Detecting Keys and Values in a Hash
Determining whether a key has been assigned can be done with has_key? or any one of its aliases include?, key?, and member?:
a = {"a"=>1,"b"=>2} a.has_key? "c" # false a.include? "a" # true a.key? 2 # false a.member? "b" # true
You can also use empty? to see whether any keys at all are left in the hash. Likewise length or its alias size can be used to determine how many there are:
a.empty? # false a.length # 2
Alternatively, you can test for the existence of an associated value using has_value? or value?:
a.has_value? 2 # true a.value? 99 # false
8.2.8. Extracting Hashes into Arrays
To convert the entire hash into an array, use the to_a method. In the resulting array, keys will be even-numbered elements (starting with 0), and values will be odd-numbered elements of the array:
h = {"a"=>1,"b"=>2} h.to_a # ["a",1,"b",2]
It is also possible to convert only the keys or only the values of the hash into an array:
h.keys # ["a","b"] h.values # [1,2]
Finally, you can extract an array of values selectively based on a list of keys, using the method. This works for hashes much as the method of the same name works for arrays. (Also, as for arrays, values_at replaces the obsolete methods indices and indexes.)
h = {1=>"one",2=>"two",3=>"three",4=>"four","cinco"=>"five"} h.values_at(3,"cinco",4) # ["three","five","four"] h.values_at(1,3) # ["one","three"]
8.2.9. Selecting Key-Value Pairs by Criteria
The Hash class mixes in the Enumerable module, so you can use detect (find), select, (find_all), grep, min, max, and reject as with arrays.
The detect method (alias find) finds a single key-value pair. It takes a block (into which the pairs are passed one at a time) and returns the first pair for which the block evaluates to TRue.
names = {"fred"=>"jones","jane"=>"tucker", "joe"=>"tucker","mary"=>"SMITH"} # Find a tucker names.detect {|k,v| v=="tucker" } # ["joe","tucker"] # Find a capitalized surname names.find {|k,v| v==v.upcase } # ["mary", "SMITH"]
Of course, the objects in the hash can be of arbitrary complexity, as can the test in the block, but comparisons between differing types can cause problems.
The select method (alias find_all) returns multiple matches as opposed to a single match:
names.select {|k,v| v=="tucker" } # [["joe", "tucker"], ["jane", "tucker"]] names.find_all {|k,v| k.count("r")>0} # [["mary", "SMITH"], ["fred", "jones"]]
8.2.10. Sorting a Hash
Hashes are by their nature not ordered according to the value of their keys or associated values. In performing a sort on a hash, Ruby converts the hash to an array and then sorts that array. The result is naturally an array.
names = {"Jack"=>"Ruby","Monty"=>"Python", "Blaise"=>"Pascal", "Minnie"=>"Perl"} list = names.sort # list is now: # [["Blaise","Pascal"], ["Jack","Ruby"], # ["Minnie","Perl"], ["Monty","Python"]]
8.2.11. Merging Two Hashes
Merging hashes may be useful sometimes. Ruby's merge method merges the entries of two hashes, forming a third hash and overwriting any previous duplicates:
dict = {"base"=>"foundation", "pedestal"=>"base"} added = {"base"=>"non-acid", "salt"=>"NaCl"} new_dict = dict.merge(added) # {"base"=>"non-acid", "pedestal"=>"base", "salt"=>"NaCl"}
An alias for merge is update.
If a block is specified, it can contain logic to deal with collisions. For example, here we assume that if we have two keys colliding, we use the value that is less than the other (alphabetically, numerically, or however):
dict = {"base"=>"foundation", "pedestal"=>"base"} added = {"base"=>"non-acid", "salt"=>"NaCl"} new_dict = dict.merge(added) {|key,old,new| old < new ? old : new } # {"salt"=>"NaCl", "pedestal"=>"base", "base"=>"foundation"}
The second result using the block is thus different from the previous example. Also be aware that there are mutator methods merge! and update!, which will change the receiver in place.
8.2.12. Creating a Hash from an Array
The easiest way to do this is to remember the bracket notation for creating hashes. This works if the array has an even number of elements.
array = [2, 3, 4, 5, 6, 7] hash = Hash[*array] # hash is now: {2=>3, 4=>5, 6=>7}
8.2.13. Finding Difference or Intersection of Hash Keys
Since the keys of a hash can be extracted as a separate array, the extracted arrays of different hashes can be manipulated using the Array class methods & and - to produce the intersection and difference of the keys. The matching values can be generated with the each method performed on a third hash representing the merge of the two hashes (to ensure all keys can be found in one place).
a = {"a"=>1,"b"=>2,"z"=>3} b = {"x"=>99,"y"=>88,"z"=>77} intersection = a.keys & b.keys difference = a.keys - b.keys c = a.dup.update(b) inter = {} intersection.each {|k| inter[k]=c[k] } # inter is {"z"=>77} diff={} difference.each {|k| diff[k]=c[k] } # diff is {"a"=>1, "b"=>2}
8.2.14. Using a Hash As a Sparse Matrix
Often we want to use an array or matrix that is nearly empty. We could store it in the conventional way, but this is often wasteful of memory. A hash provides a way to store only the values that actually exist.
In the following example we assume that the nonexistent values should default to zero:
values = Hash.new(0) values[1001] = 5 values[2010] = 7 values[9237] = 9 x = values[9237] # 9 y = values[5005] # 0
Obviously, in the preceding example, an array would have created more than 9,000 unused elements. This may not be acceptable.
What if we want to implement a sparse matrix of two or more dimensions? All we need do is use arrays as the hash keys:
cube = Hash.new(0) cube[[2000,2000,2000]] = 2 z = cube[[36,24,36]] # 0
In this case, we see that literally billions of array elements would need to be created if this three-dimensional matrix were to be complete.
8.2.15. Implementing a Hash with Duplicate Keys
Purists would likely say that if a hash has duplicate keys, it isn't really a hash. We don't want to argue. Call it what you will; there might be occasions where you want a data structure that offers the flexibility and convenience of a hash but allows duplicate key values.
We offer a partial solution here (Listing 8.1). It is partial for two reasons. First, we have not bothered to implement all the functionality that could be desired but only a good representative subset. Second, the inner workings of Ruby are such that a hash literal is always an instance of the Hash class, and even though we were to inherit from Hash, a literal would not be allowed to contain duplicates. (We're thinking about this one further.)
Listing 8.1. Hash with Duplicate Keys
class HashDup def initialize(*all) raise IndexError if all.size % 2 != 0 @store = {} if all[0] # not nil keyval = all.dup while !keyval.empty? key = keyval.shift if @store.has_key?(key) @store[key] += [keyval.shift] else @store[key] = [keyval.shift] end end end end def store(k,v) if @store.has_key?(k) @store[k] += [v] else @store[k] = [v] end end def [](key) @store[key] end def []=(key,value) self.store(key,value) end def to_s @store.to_s end def to_a @store.to_a end def inspect @store.inspect end def keys result=[] @store.each do |k,v| result += ([k]*v.size) end result end def values @store.values.flatten end def each @store.each {|k,v| v.each {|y| yield k,y}} end alias each_pair each def each_key self.keys.each {|k| yield k} end def each_value self.values.each {|v| yield v} end def has_key? k self.keys.include? k end def has_value? v self.values.include? v end def length self.values.size end alias size length def delete k val = @store[k] @store.delete k val end def delete k,v @store[k] -= [v] if @store[k] v end # Other methods omitted here... end # This won't work... dup key will ignore # first occurrence. h = {1=>1, 2=>4, 3=>9, 4=>16, 2=>0} # This will work... h = HashDup.new(1,1, 2,4, 3,9, 4,16, 2,0) k = h.keys # [4, 1, 2, 2, 3] v = h.values # [16, 1, 4, 0, 9] n = h.size # 5 h.each {|k,v| puts "#{k} => #{v}"} # Prints: # 4 => 16 # 1 => 1 # 2 => 4 # 2 => 0 # 3 => 9 |
But as long as you stay away from the hash-literal notation, this problem is doable. In Listing 8.1 we implement a class that has a "store" (@store), which is a simple hash; each value in the hash is an array. We control access to the hash in such a way that when we find ourselves adding a key that already exists, we add the value to the existing array of items associated with that key.
What should size return? Obviously the "real" number of key-value pairs including duplicates. Likewise the keys method returns a value potentially containing duplicates. The iterators behave as expected; as with a normal hash, there is no predicting the order in which the pairs will be visited.
Besides the usual delete, we have implemented a delete_pair method. The former deletes all values associated with a key; the latter deletes only the specified key-value pair. (Note that it would have been difficult to make a single method like delete(k,v=nil) because nil is a valid value for any hash.
For brevity we have not implemented the entire class, and, frankly, some of the methods such as invert would require some design decisions as to what their behavior should be. The interested reader can flesh out the rest as needed.
发表评论
-
Query
2008-01-31 17:39 48class System::FastQuery de ... -
Fast Query
2008-01-19 15:07 4037class System::FastQuery def s ... -
9.3. Working with Trees
2008-01-19 15:06 3830I think that I shall never se ... -
9.2. Working with Stacks and Queues
2008-01-19 15:04 3760Stacks and queues are the first ... -
9.1. Working with Sets
2008-01-19 15:03 3387We've already seen how certain ... -
8.3. Enumerables in General
2008-01-19 14:26 3531What makes a collection enumera ... -
计算两个字符串之间的Levenshtein距离
2008-01-09 23:32 5219Levenshtein距离 class String ... -
字符串的编码和解码
2008-01-09 23:11 3844rot13编码和解码 class String def r ... -
rails应用自动化部署——使用capistrano2.0
2007-10-10 18:59 6305昨天用capistrano2.0把应用部署搞的比较自动化了一点 ... -
selenium和ajax的测试问题
2007-08-13 15:51 6635Hi,all I am having doubts in se ... -
在selenium测试中使用ActiveRecord
2007-08-10 18:15 5147ActiveRecord是rails的框架,我们在seleni ... -
关于rails应用的验收测试
2007-08-08 18:26 4772ruby的测试运行的本来都慢,selenium的验收测试跑起来 ... -
Exception: Bad file descriptor - connect(2)
2007-08-07 15:59 5496Hi,all I am trying to test web ...
相关推荐
Python参考手册,官方正式版参考手册,chm版。以下摘取部分内容:Navigation index modules | next | Python » 3.6.5 Documentation » Python Documentation contents What’s New in Python ...PEP 343: The ‘with...
hasher = hashes.Hash(hashes.SHA256(), backend=default_backend()) hasher.update(b"数据") digest = hasher.finalize() ``` 四、数字签名 数字签名用于验证信息的完整性和发送者身份。`cryptography`库中的`...
Redis 支持多种数据类型,如字符串(strings)、哈希(hashes)、列表(lists)、集合(sets)、有序集合(sorted sets)等。以下是一些 Redis 命令的实践示例: 1. 字符串(Strings) 设置值 bash redis-cli SET ...
Introduction -------------------------------- RainbowCrack is a general propose implementation of Philippe Oechslin's faster time-memory trade-off technique. It cracks hashes with rainbow tables.
javascript-Hashes.rar
Understand and implement classic data structures and algorithms using JavaScript ... Dictionaries and Hashes Chapter 8. Trees Chapter 9. Graphs Chapter 10. Sorting and Searching Algorithms
sha256_hash = hashes.Hash(hashes.SHA256(), backend=default_backend()) sha256_hash.update(message) digest = sha256_hash.finalize() ``` 5. **证书和公钥基础设施(PKI)**:`cryptography`还提供了生成和...
Section 8.2. Notation Section 8.3. Groups Section 8.4. Fields Section 8.5. Mathematics of Rijndael Section 8.6. Elliptic Curve Cryptography Section 8.7. Homework Part 2: Authentication ...
《PyPI官网下载 | d8s_hashes-0.6.0.tar.gz——深入解析Python库的发布与使用》 PyPI(Python Package Index)是Python开发者的重要资源库,它为全球Python用户提供了丰富的第三方模块和库,使得开发变得更加便捷...
python官网-哈希hashes.rar
C11 + Pthreads 原子有界工作队列 这是一个使用 C11 的stdatomic.h特性提供单写入器、多读取器无锁队列 (lqueue) 的小型库。... compute hashes ... */ } void sha1_compute_all ( void ) { int nthreads = sysc
React本机 React Native的基本椭圆曲线加密 使用此模块 安装 请参阅 用法 import * as ec from 'react-native-ecc' import { Buffer } from...// this library allows you to sign 32 byte hashes (e.g. sha256 hashes)
mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH ), hashes.SHA256() ) # 使用公钥验证签名 try: public_key.verify( signature, message, padding.PSS( mgf=padding.MGF1(hashes...
-v : Verify hashes. : Option: -bp basepath. -? -h -help : Extended Help. Options: -md5 | -sha1 | -both : Specify hashtype, default md5. -xml db : Specify database format and name. To display ...
with open('file.txt', 'rb') as f: md5_hash = hashlib.md5() chunk = f.read(8192) while chunk: md5_hash.update(chunk) chunk = f.read(8192) print('MD5 Hash:', md5_hash.hexdigest()) ``` 此外,`...
jquery.hash jQuery DOM元素哈希插件 支持的哈希方法 base64 md5 sha1 自己编译 如果要编译自己的版本或jquery.hash的修改 ...hashes . push ( $ . hashing . base64 ( "Hello jQuery!" ) ) ; /
mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None ) ) # 解密 decrypted_text = private_key.decrypt( ciphertext, padding.OAEP( mgf=padding.MGF1(algorithm=hashes....
提取哈希.py 该脚本读取文件并尝试使用正则表达式从中提取哈希值。... python extract-hash.py hashes.txt extract-hash.py: Extracts hashes from a text file Extracted hashes: wordpress_md5: 5 md5: 192
h = hashes.Hash(hashes.SHA256(), backend=default_backend()) h.update(message) digest = h.finalize() ``` 六、数字签名 数字签名用于验证信息的完整性和发送者的身份: ```python from cryptography.hazmat....