行ごとにテーブルへのアクセスを提供し、メモリをより効率的に使用し、dictクラスをより自然に使用しようとするために、Dugresの回答を変更します。この例では、行キーは0から数えて単純な数値列挙からのものです。
columns = ['col1', 'col2']
table = [
['abc', 123],
['def', 456],
['ghi', 123],
]
# build view from a comprehension
view = {i: {columns[j]: table[i][j] for j in range(len(columns))} for i in range(len(table))}
# build view procedurally
view = dict()
for i, row in enumerate(table):
view[i] = dict()
for j, col in enumerate(row):
view[i][columns[j]] = col
# view contents
view
{0: {'col2': 123, 'col1': 'abc'},
1: {'col2': 456, 'col1': 'def'},
2: {'col2': 123, 'col1': 'ghi'}}
# Cell by row and column
>>> view[0]['col1']
'abc'
# List of cells for row 0:
>>> [view[0][col] for col in columns]
['abc', 123]
# All cells in col2:
>>> [view[row]['col2'] for row in sorted(view.keys())]
[123, 456, 123]
# All rows with value 123 in col2, using a list generator expression
[[view[row][column] for column in columns] for row in view.keys() for col in columns if view[row][col] == 123]
[['abc', 123], ['ghi', 123]]
# All rows with value 123 in col2, using a list generator function
def rowGenerator(view, col, value):
for row in view.keys():
if view[row][col] == value:
yield [view[row][colName] for colName in columns]
>>> [row for row in rowGenerator(view, 'col2', 123)]
[['abc', 123], ['ghi', 123]]