I have this dataset:
[('Stuff', ' ')
('Available in several colors.', ' ')
('A fits B by Sometimes.', ' ')
('handle $148', 'A ')
('handle base $23', 'A ')
('mirror base $24', 'A ')
(' handle $31', 'B ')
('handle base, $23', 'B ')
('Mirror $24', 'B ')
]
What I need to do is print this data with a "header" based off the second item in the list. Only printing the header when it changes. In this sample, the only 3 options are " ", "A ", and "B ". But in my actual data set there could be 100+ different options, so hard coding them in is not really an options.
I want the printed data to look like this (skipping the " ")
Stuff.
Available in several colors.
A fits B by Sometimes.
A ----------------------
handle $148
handle base $23
mirror base $24
B ----------------------
handle $31
handle base, $23
Mirror $24
the only way to do this I can think of is to hard code the values in, but with 100+ possibilities this would take forever. There must be a better way.
a_printed = False
b_printed = False
for item in list1:
if item[1] == ' ':
print(item[0])
elif item[1] == 'A ':
if a_printed != True:
print('A --------------')
a_printed = True
print(item[0])
elif item[1] == 'B ':
if b_printed != True:
print('B --------------')
b_printed = True
print(item[0])
Any help is appreciated.
>Solution :
You don’t need to hard-code the header values, just set a variable to the header and test if the new header is different.
last_header = ' '
for value, header in list1:
if header != last_header:
print(header, '--------------')
last_header = header
print value