What first pops into my head is a dictionary with keys acting as list values and dictionary values defaulting to None
, but this feels sub-optimal to me. Can anyone propose a single-structure (i.e. no separate 'options' dict) alternative where dict[key]
on an item with no flags set retur开发者_StackOverflowns None
and otherwise returns a list of flags? Apologies if I am overlooking some obvious convention.
A simple use for this structure could be an order
instance where each item can optionally contain modifications (i.e. no nuts).
Maybe a defaultdict will do:
from collections import defaultdict
flags = defaultdict(lambda : None)
flags.update({'F1':True,'F3':True,'F8':True})
for f in 'F1 F2 F3 F4 F5 F6 F7 F8'.split():
print f, '->', flags[f]
Prints:
F1 -> True
F2 -> None
F3 -> True
F4 -> None
F5 -> None
F6 -> None
F7 -> None
F8 -> True
A couple of possibilities:
1) dict.get(key, None)
returns None
if there is no entry for key
.
2) dict = defaultdict( lambda: None )
creates a dict that automatically returns None
if there is no entry for a given key.
As you may have gathered from my comments above, I'm not sure exactly what your real requirements are. But my guess is that they're a little different from what's implied by the suggestions of a defaultdict
. It sounds to me as if you want a list of items (ordered, perhaps with repetitions allowed), each associated with a perhaps-empty set of flags. In which case, the simplest solution is probably a list of pairs (item,flags)
, where each flags
is a set object.
This doesn't give you the ability to look up the flags by the value of item
, but that doesn't sound to me like something you should be doing anyway. (Taking your restaurant-order example, there might be two people whose item
is, say, HouseSalad
, but only one of them might have the no_nuts
flag.)
You can of course get a list of flags from each item's set just by calling list
on it.
In any specific application, it might well be worth making a class to hold this information and provide more transparent ways of accessing it. That would make it easier to add in extra features if you realise you need them (random example: the ability to find all items with a given flag).
精彩评论