I want to collect data and represent it as given below, but not sure what data type to use, in case of c an multi dimension array will do the job.
Box 1 Box 2 Box 3
Red 5 8 3
Yellow 3 7 2
Blue 5 4 9
The number of box and the colours are not predefined. I create this by reading file box1, box2 .....
-
Not sure if I understand. Do you want a data structure to represent a table with markup in the cells? How do you derive the markup from the data?bereal– bereal2015年03月11日 07:48:32 +00:00Commented Mar 11, 2015 at 7:48
-
can you share your code?Heisenberg– Heisenberg2015年03月12日 04:23:10 +00:00Commented Mar 12, 2015 at 4:23
3 Answers 3
You can use dictionary {color : list of box count}.
e.g.
>>> colors = {}
>>> colors["red"] = [1,2,3] #you can dynamically add to list while reading files.
>>> colors["yellow"] = [0,2,4]
>>> colors
{'yellow': [0, 2, 4], 'red': [1, 2, 3]}
then you can iterate over the dictionary and print data as you want.
2 Comments
@Heisenberg suggest solution with unsorted dict. But if need order of added items you can use next solution:
from collections import OrderedDict
class Colors(OrderedDict):
"""Store colors in depend from added order"""
def __setitem__(self, color, value):
if color in self:
del self[color]
OrderedDict.__setitem__(self, color, value)
colors_table = Colors()
colors_table["red"] = [1,2,3]
colors_table["yellow"] = [0,2,4]
colors_table["blue"] = [2,3,4]
print colors_table # print Colors([('red', [1, 2, 3]), ('yellow', [0, 2, 4]), ('blue', [2, 3, 4])])
1 Comment
You can use multi-dimensional array in python as well, but in a slightly different manner. Here it will be an array of arrays. So your data structure will look something like:
matrix = [
['Color', 'Box1', 'Box2', 'Box3'],
['Red', 5, 8, 3],
['Yellow', 3, 7, 2],
['Blue', 5, 4, 9]
]