开发者

I've been using dictionary keys as membership markers. Is this a good idea?

开发者 https://www.devze.com 2023-01-30 19:39 出处:网络
For instance, I have a document that has a pile of control codes that I need to manually specify replacements for. I basically write a script that prints out the list of codes. Easy.

For instance, I have a document that has a pile of control codes that I need to manually specify replacements for. I basically write a script that prints out the list of codes. Easy.

Now I've been using a dictionary's k开发者_如何学JAVAey to store the membership. If the code exists, then I set the dictionary value to something, and then I just return the keys of that dictionary. This strikes me as a little wasteful. Is there any better way of doing things?


You should use a set instead.

>>> members = set()
>>> members.add(1)
>>> 1 in members
True
>>> 2 in members
False

If your codes are stored in an iterable then finding the unique codes might be as as simple as:

>>> set(codes)
0

精彩评论

暂无评论...
验证码 换一张
取 消