[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

This works about the same as the previous version, even though the internal imple-
mentation is radically different:


>>> from fastset import Set
>>> users1 = Set(['Bob', 'Emily', 'Howard', 'Peeper'])
>>> users2 = Set(['Jerry', 'Howard', 'Carol'])
>>> users3 = Set(['Emily', 'Carol'])
>>> users1 & users2
<Set:['Howard']>
>>> users1 | users2
<Set:['Howard', 'Peeper', 'Jerry', 'Carol', 'Bob', 'Emily']>
>>> users1 | users2 & users3
<Set:['Peeper', 'Carol', 'Howard', 'Bob', 'Emily']>
>>> (users1 | users2) & users3
<Set:['Carol', 'Emily']>
>>> users1.data
{'Peeper': None, 'Bob': None, 'Howard': None, 'Emily': None}

The main functional difference in this version is the order of items in the set: because
dictionaries are randomly ordered, this set’s order will differ from the original. The
order of results can even vary across Python releases (in fact it did, between Python 2.X
and 3.X in the third and fourth editions of this book). For instance, you can store
compound objects in sets, but the order of items varies in this version:


>>> import set, fastset
>>> a = set.Set([(1,2), (3,4), (5,6)])
>>> b = set.Set([(3,4), (7,8)])
>>> a & b
<Set:[(3, 4)]>
>>> a | b
<Set:[(1, 2), (3, 4), (5, 6), (7, 8)]>
>>> a = fastset.Set([(1,2), (3,4), (5,6)])
>>> b = fastset.Set([(3,4), (7,8)])
>>> a & b
<Set:[(3, 4)]>
>>> a | b
<Set:[(1, 2), (5, 6), (3, 4), (7, 8)]>
>>> b | a
<Set:[(1, 2), (5, 6), (3, 4), (7, 8)]>

Sets aren’t supposed to be ordered anyhow, so this isn’t a showstopper. A deviation
that might matter, though, is that this version cannot be used to store unhashable (that
is, immutable) objects. This stems from the fact that dictionary keys must be immutable.
Because values are stored in keys, dictionary sets can contain only things such as tuples,
strings, numbers, and class objects with immutable signatures. Mutable objects such
as lists and dictionaries won’t work directly in this dictionary-based set, but do in the
original set class. Tuples do work here as compound set items, though, because they
are immutable; Python computes hash values and tests key equality as expected:


>>> set.Set([[1, 2],[3, 4]])
<Set:[[1, 2], [3, 4]]>
>>> fastset.Set([[1, 2],[3, 4]])
TypeError: unhashable type: 'list'

1380 | Chapter 18: Data Structures

Free download pdf