Python 3.5 - 创建用生成器填充的命名元组

Python 3.5 - Creating Named Tuple Populated With Generators

试图压缩我的代码并且对 Python 还很陌生,所以如果之前的主题正好涵盖了我想要的内容,我深表歉意。我已经尝试搜索和阅读很多但收效甚微。任何帮助将不胜感激,谢谢!

(请假设单元格调用来自某个随机电子表格,其中包含按顺序显示的我需要的数据。)

import xlrd
import collections

L_col = (21, 0, 27, 24, 3, 4, 11, 35, 18, 26)
L_label = ('Room_ID', 'Name', 'Type', 'Area', 'Sens_Cooling', 'Lat_Cooling', 'Heating', 'Ventilation', 'People', 'Volume')
sp = collections.namedtuple('Space', ['Room_ID', 'Name', 'Type', 'Area', 'Sens_Cooling', 'Lat_Cooling', 'Heating',
                                      'Ventilation', 'People', 'Volume'])

a = (L_ws.cell_value(row, L_col[0]) for row in range(start, end))
b = (L_ws.cell_value(row, L_col[1]) for row in range(start, end))
c = (L_ws.cell_value(row, L_col[2]) for row in range(start, end))
d = (L_ws.cell_value(row, L_col[3]) for row in range(start, end))
e = (L_ws.cell_value(row, L_col[4]) for row in range(start, end))
f = (L_ws.cell_value(row, L_col[5]) for row in range(start, end))
g = (L_ws.cell_value(row, L_col[6]) for row in range(start, end))
h = (L_ws.cell_value(row, L_col[7]) for row in range(start, end))
i = (L_ws.cell_value(row, L_col[8]) for row in range(start, end))
j = (L_ws.cell_value(row, L_col[9]) for row in range(start, end))

rs = sp(a, b, c, d, e, f, g, h, i, j)

您可以执行以下操作:

import xlrd
import collections

def create_gen(column, start, end):
    return (L_ws.cell_value(row, column) for row in range(start, end))

L_col = (21, 0, 27, 24, 3, 4, 11, 35, 18, 26)
L_label = ('Room_ID', 'Name', 'Type', 'Area', 'Sens_Cooling', 'Lat_Cooling', 'Heating', 'Ventilation', 'People', 'Volume')
sp = collections.namedtuple('Space', L_label)
rs = sp(*(create_gen(col, start, end) for col in L_col))

因为您已经在 L_label 中有了字段名称,您可以将其传递给 namedtuple 而不是创建另一个列表。

对于生成器,您可以编写遍历 L_col 中的列的生成器表达式。对于每一列,生成器表达式都会调用一个单独的方法,该方法 returns 生成器就像您之前创建的那样。请注意,您需要在此处使用 closure,因为在调用生成器时会计算 col。最后,结果在传递给 sp.

之前用 * 运算符解包

在我看来你可以做到:

items = [
    [L_ws.cell_value(row, L_col[i]) for row in range(start, end)]
    for i in range(10)]
rs = sp(*items)

如果您需要在项目中使用生成器,我建议您使用生成器函数:

def gen_item(column_number):
    for row_number in range(start, end):
        yield L_ws.cell_value(row_number, L_col[column_number])

rs = sp(*(gen_item(i) for i in range(10)))

此生成器假定 startendL_col 是通过闭包获取的。如果您愿意,可以将它们作为参数传递。

另外,你上面有一点重复:

L_label = ('Room_ID', 'Name', 'Type', 'Area', 'Sens_Cooling', 'Lat_Cooling', 'Heating', 'Ventilation', 'People', 'Volume')
sp = collections.namedtuple('Space', ['Room_ID', 'Name', 'Type', 'Area', 'Sens_Cooling', 'Lat_Cooling', 'Heating',
                                      'Ventilation', 'People', 'Volume'])

可能只是:

L_label = ('Room_ID', 'Name', 'Type', 'Area', 'Sens_Cooling', 'Lat_Cooling', 'Heating', 'Ventilation', 'People', 'Volume')
sp = collections.namedtuple('Space', L_label)

话虽如此......将生成器表达式放入命名元组中感觉有点奇怪(尽管没有很好的理由说明你 也不能 ) ...