我会修改Dugres的答案,以便按行提供对表的访问,更有效地使用内存并尝试更自然地使用 dict 类。在此示例中,行键来自一个简单的数字枚举,从 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]]