Real world application: categorize bytes into the categories: control, printable, non-printable character (category list will be longer)
I have a list of numbers:
numbers = [1, 1, 2, 3, 3, 3, 3, 4]
Now I want to put them into different categories. To do so, I have to define in which category a number belongs. So far I have two approaches, both using a predefined index/value pair.
category_list = ["apple", "apple", "banana", "melon", "melon", "melon"]
category_dict = {1 : "apple", 2 : "apple", 3 : "banana", 4 : "melon", 5 : "melon", 6 : "melon"}
for number in numbers:
print category_list[number]
category_dict[number]
Another option would be a list for every category. This is eventually faster to write/implement but forces me to brute-force the dictionary (see one of the answers):
dict_category = {
apple : [1, 2],
banana : [3,],
melon : [4, 5, 6]
}
for number in numbers:
for key, val in dict_category.iteritems():
if number in val:
print key
break
Is there a better, more pythonic way to do this? Maybe which doesn’t require me to write a list/dict with 256 entries?
If your numbers are within a certain range, you could also use a vector for lookup: