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

(yzsuai) #1

res.append(x)
return res


These functions work on any type of sequence—lists strings, tuples, and other iterable
objects that conform to the protocols expected by these functions (for loops, in mem-
bership tests). In fact, we can even use them on mixed object types: the last two com-
mands in the following test compute the intersection and union of a list and a tuple.
As usual in Python, the object interface is what matters, not the specific types:


C:\...\PP4E\Dstruct\Basic> python
>>> from inter import *
>>> s1 = "SPAM"
>>> s2 = "SCAM"
>>> intersect(s1, s2), union(s1, s2)
(['S', 'A', 'M'], ['S', 'P', 'A', 'M', 'C'])
>>> intersect([1,2,3], (1,4))
[1]
>>> union([1,2,3], (1,4))
[1, 2, 3, 4]

Notice that the result is always a list here, regardless of the type of sequences passed
in. We could work around this by converting types or by using a class to sidestep this
issue (and we will in a moment). But type conversions aren’t clear-cut if the operands
are mixed-type sequences. Which type do we convert to?


Supporting multiple operands


If we’re going to use the intersect and union functions as general tools, one useful
extension is support for multiple arguments (i.e., more than two). The functions in
Example 18-9 use Python’s variable-length argument lists feature to compute the in-
tersection and union of arbitrarily many operands.


Example 18-9. PP4E\Dstruct\Basic\inter2.py


"set operations for multiple sequences"


def intersect(*args):
res = []
for x in args[0]: # scan the first list
for other in args[1:]: # for all other arguments
if x not in other: break # this item in each one?
else:
res.append(x) # add common items to the end
return res


def union(*args):
res = []
for seq in args: # for all sequence-arguments
for x in seq: # for all nodes in argument
if not x in res:
res.append(x) # add new items to result
return res


1376 | Chapter 18: Data Structures

Free download pdf