[Tutor] working with multiple sets
kevin parks
kp8 at me.com
Tue Sep 8 16:07:02 CEST 2009
I also notice that if i do:
def foo():
lookup = collections.defaultdict(list)
x = range(10)
y = range(5, 15)
z = range(8, 22)
sets = {'x': set(x), 'y': set(y), 'z': set(z)}
for key, value in sets.items():
for element in value:
lookup[element].append(key)
for x in lookup:
print x, lookup[x]
print
in oder to print more clearly what I want to see, the sets (as usual
for a mapping type) are not always in order. Note that from 5 to 7 for
example 'y' is listed in front of 'x' and 8 & 9 have 'y', 'x', 'z' and
not 'x', 'y', 'z' ... I am not clear on how to sort that as the
dictionary method lookup.sort() either doesn't work or i have tried
it in all the wrong places.
0 ['x']
1 ['x']
2 ['x']
3 ['x']
4 ['x']
5 ['y', 'x']
6 ['y', 'x']
7 ['y', 'x']
8 ['y', 'x', 'z']
9 ['y', 'x', 'z']
10 ['y', 'z']
11 ['y', 'z']
12 ['y', 'z']
13 ['y', 'z']
14 ['y', 'z']
15 ['z']
16 ['z']
17 ['z']
18 ['z']
19 ['z']
20 ['z']
21 ['z']
On Sep 8, 2009, at 10:52 PM, bob gailer wrote:
> kevin parks wrote:
>>
>>
>> I am looking at this and wondering:
>>
>> Why does this use collections.defaultdict ?
>>
>> In fact i guess since collections.defaultdict is new to me i am not
>> even sure why it exists
>> and why someone would use this as opposed to using Python's built-
>> in dictionary? and why was it
>> used in this instance?
>
> It simplifies coding, as it takes care of initializing each new
> entry to a list.
>
>> On Sep 6, 2009, at 3:06 AM, bob gailer wrote:
>>
>>>
>>>
>>> I want to be able to look at a number/item and see which lists it
>>> is in so that i could maybe have a master list of all the data, a
>>> superset, and then an indication of which lists that data was in,
>>> as some items will only be in one list, some will appear in two
>>> lists (x & y, or x & z or y & z) and a small handful will be in
>>> all three lists.
>>>
>>> I think you mean "set" rather than "list"
>>>
>>> To enable processing of an arbitrary number of sets, put them in a
>>> collection (list or dictionary). Use a list if it is sufficient to
>>> identify sets by number, else use a dictionary.
>>>
>>> Use a dictionary to relate items to their set(s).
>>>
>>> import collections
>>> lookup = collections.defaultdict(list)
>>> sets = {'x': set((1,2,3)), 'y': set((2,3))}
>>> for key, value in sets.items():
>>> for element in value:
>>> lookup[element].append(key)
>>> print lookup
>>>
>>>
> --
> Bob Gailer
> Chapel Hill NC
> 919-636-4239
More information about the Tutor
mailing list