I have an existing python3 tuple withdrawn from an sqlite3 table with dates "??-??-22" per row in accordance with the insertion date. I would like to insert another element in the python3 tuple that matches the date properly. In this case, an increment of a day number matching the date change. The number of rows per day are sometimes inconsistent. Hence, I am not inserting tuple back into database....Just using it for data visualization.
For example, [('06-08-22',otherData), ('06-08-22',), ('06-08-22',), ('06-08-22',), ('06-08-22',), ('06-09-22',), ('06-09-22',), ('06-09-22',), ...etc )]
------>>>
[('06-08-22',Day Number Here,), ('06-08-22',1,), ('06-08-22',1,), ('06-08-22',1,), ('06-08-22',1,), ('06-09-22',2,), ('06-09-22',2,), ('06-09-22',2,), ...etc )]
Solve by a for loop? Feels like overlooking something simple.
CodePudding user response:
You cannot insert new elements into a tuple, so you will have to convert each tuple to a list and then back to a tuple (or just leave them as lists if you don't really need them to stay tuples)
data = [
('06-08-22', 'A'),
('06-08-22', 'B'),
('06-09-22', 'C'),
('06-10-22', 'D'),
('06-10-22', 'E')
]
def transform_data(rows):
day_num = 0
last_date = None
for row in rows:
lst = list(row)
if lst[0] != last_date:
last_date = lst[0]
day_num = 1
lst.insert(1, day_num)
yield tuple(lst)
for row in transform_data(data):
print(row)
Output:
('06-08-22', 1, 'A')
('06-08-22', 1, 'B')
('06-09-22', 2, 'C')
('06-10-22', 3, 'D')
('06-10-22', 3, 'E')
CodePudding user response:
If the records are sorted by day you could use groupby()
and do
from itertools import groupby
from operator import itemgetter
records = [
('06-08-22', "A"),
('06-08-22',),
('06-08-22', "B"),
('06-08-22', "C"),
('06-08-22',),
('06-09-22', "D", "E"),
('06-09-22',),
('06-09-22', "F"),
('06-09-23',),
]
result = []
for n, (day, group) in enumerate(
groupby(records, key=itemgetter(0)), start=1
):
result.extend((day, n) record[1:] for record in group)
which gives you the following result
:
[('06-08-22', 1, 'A'),
('06-08-22', 1),
('06-08-22', 1, 'B'),
('06-08-22', 1, 'C'),
('06-08-22', 1),
('06-09-22', 2, 'D', 'E'),
('06-09-22', 2),
('06-09-22', 2, 'F'),
('06-09-23', 3)]