Skip to main content
 首页 » 编程设计

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

2024年10月24日6lidabo

试图压缩我的代码并且我对 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) 

请您参考如下方法:

在我看来你可以这样做:

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

此生成器假定 start、end 和 L_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) 

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