正在尝试压缩我的代码,并且我对 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)
话虽如此......将生成器表达式放入命名元组中感觉有点奇怪(尽管也没有很好的理由为什么你不能)...
关于Python 3.5 - 创建填充有生成器的命名元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37095271/