gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:13:36 25 4
gpt4 key购买 nike

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

此生成器假定 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)

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

关于Python 3.5 - 创建用生成器填充的命名元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37095271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com