Reputation: 452
I have a Python List and I have implemented a click listener for the items in, if i have the index of an item in that list,
E.g, I can get the text ( 'text': '0000' ), where index = 3 or the text ('text': '100') where index = 24, how can use an index of the item to print all the other data in row in which that index lies?
data = [{'text': '400'}, {'text': 'Dairy'}, {'text': '0000'}, {'text': 'Milkshake'}, {'text': '500'}, {'text': 'Available'}, {'text': '0.0'}, {'text': '1'}, {'text': 'Kisumu'},
{'text': '500'}, {'text': 'Electronics'}, {'text': '1111'}, {'text': 'Flower'}, {'text': '700'}, {'text': 'Available'}, {'text': '50'}, {'text': '2'}, {'text': 'Kisumu'},
{'text': '500'}, {'text': 'Electronics'}, {'text': '8888'}, {'text': 'Eggs'}, {'text': '900'}, {'text': 'Unavailable'}, {'text': '100'}, {'text': '5'}, {'text': 'Kisumu'}]
Upvotes: 0
Views: 382
Reputation: 11342
Another way...
data = [{'text': '400'}, {'text': 'Dairy'}, {'text': '0000'}, {'text': 'Milkshake'}, {'text': '500'}, {'text': 'Available'}, {'text': '0.0'}, {'text': '1'}, {'text': 'Kisumu'},
{'text': '500'}, {'text': 'Electronics'}, {'text': '1111'}, {'text': 'Flower'}, {'text': '700'}, {'text': 'Available'}, {'text': '50'}, {'text': '2'}, {'text': 'Kisumu'},
{'text': '500'}, {'text': 'Electronics'}, {'text': '8888'}, {'text': 'Eggs'}, {'text': '900'}, {'text': 'Unavailable'}, {'text': '100'}, {'text': '5'}, {'text': 'Kisumu'}]
rows = [data[x:x+9] for x in range(0,len(data),9)] # split to rows
idx = 24
print(rows[idx//9])
Output
[{'text': '500'}, {'text': 'Electronics'}, {'text': '8888'}, {'text': 'Eggs'}, {'text': '900'}, {'text': 'Unavailable'}, {'text': '100'}, {'text': '5'}, {'text': 'Kisumu'}]
Upvotes: 2
Reputation: 1597
def get_row_range(index:int, num_cols:int) -> range:
# index - index, which you want the row of
# num_cols - number of columns in your table
row = int(index/num_cols) # the row you want
return range(row * num_cols, (row+1)*num_cols) # the range which that index lies
# Example usage of querying the index '10'
clicked_index = 10 # in the event handler get which index was clicked
num_cols = 9 # your example has 9 columns
for i in get_row_range(clicked_index, num_cols):
print(data[i]["text"])
Upvotes: 1