使用数据索引打印Python列表中一行中的所有项

2024-09-30 14:25:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Python列表,我为中的项目实现了一个单击侦听器,如果我有该列表中某个项目的索引

例如,我可以得到文本('text':'0000'),其中index=3或文本('text':'100'),其中index=24, 如何使用该项的索引打印该索引所在行中的所有其他数据

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'}]

诊断数据 Diagramatic data


Tags: 数据项目text文本列表dataindexeggs
2条回答
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"])

另一种方式

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])

输出

[{'text': '500'}, {'text': 'Electronics'}, {'text': '8888'}, {'text': 'Eggs'}, {'text': '900'}, {'text': 'Unavailable'}, {'text': '100'}, {'text': '5'}, {'text': 'Kisumu'}]

相关问题 更多 >