sets and subsets

François Pinard pinard at iro.umontreal.ca
Wed Feb 11 18:57:15 EST 2004


[Peter Otten]

> (untested)
> from sets import set

> inputFile = file('ips.txt', 'r') #Super-set
> include = Set(inputFile.readlines())
> inputFile.close()

> readFile = file('excluded_ips.txt', 'r') #Sub-set to exclude
> exclude = Set(readFile.readlines())
> readFile.close()

> # No Magic of Elaine

> outputFile = file('pruned_ips.txt' , 'w')
> for i in include - exclude:
>     print >> outputFile, i,
> outputFile.close()

Here is an equivalent, shorter algorithm (tested):

from sets import Set
file('pruned_ips.txt', 'w').writelines(
        Set(file('ips.txt')) - Set(file('excluded_ips.txt')))

This code relies on `writelines' accepting an iterable, sets returning
their members whenever iterated, Set constructors accepting an iterable,
and files returning their lines whenever iterated.  And of course, on
`close' rarely being needed in Python! :-)

The order of lines in the produced file is kind of random, however.

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard




More information about the Python-list mailing list