I have a list of tuples. Some representation column names ( name
) and others represent the column's value ( value
).
For example: [(name, Date), (name, Units Sold), (name, Profit), (value, March 25), (value, 50), (value, 200), (name, Name), (name, Age), (value, Bob), (value, 37)]
Here, there is one table with the column names Date, Units Sold, Profit and the first row is March 25, 50, 200. The second table is Name, Age with an entry of Bob, 37.
I am trying to group the list so that I get something like this (group each group of name
/ value
):
[[(name, Date), (name, Units Sold), (name, Profit), (value, March 25), (value, 50), (value, 200)], [(name, Name), (name, Age), (value, Bob), (value, 37)]]
There is one row per table.
This should convert the entries into their respective tables (assuming 1 row per column).
flat_list=[
('name', 'Date'), ('name', 'Units Sold'), ('name', 'Profit'),
('value', 'March 25'), ('value', '50'), ('value', '200'),
('name', 'Name'), ('name', 'Age'),
('value', 'Bob'), ('value', '37')
]
def expandList(flat_list):
expanded = []
i=0
# keeps track of count of recent names
# vs recent values
values_needed = 0
while i<len(flat_list):
if flat_list[i][0]=='name':
# if values for all names have been consumed
# start a new row
if values_needed==0:
expanded.append([])
values_needed+=1
else:
values_needed-=1
# add entry to newest row
expanded[-1].append(flat_list[i])
i+=1
return expanded
expanded = expandList(flat_list)
print(expanded)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.