Python:具有可变长度参数列表的函数
我试图从Excel工作表中绘制(在同一个图上)一些数据,我想要一个长度可变的字符串列表作为输入,对应于不同的材质。我得到以下错误: TypeError:“非类型”对象不可编辑 我真的不明白为什么。代码如下:Python:具有可变长度参数列表的函数,python,matplotlib,Python,Matplotlib,我试图从Excel工作表中绘制(在同一个图上)一些数据,我想要一个长度可变的字符串列表作为输入,对应于不同的材质。我得到以下错误: TypeError:“非类型”对象不可编辑 我真的不明白为什么。代码如下: import xlrd import matplotlib.pyplot as plt from numpy import * def transmittance(*glass): wb=xlrd.open_workbook('schott_optical_glass_catalo
import xlrd
import matplotlib.pyplot as plt
from numpy import *
def transmittance(*glass):
wb=xlrd.open_workbook('schott_optical_glass_catalogue_excel_december_2012.xls')
sheet1=wb.sheet_by_index(0)
transm_index=[] #lista vuota
plt.figure(1)
plt.xlabel('wavelength $\lambda$[nm]')
plt.ylabel('transmittance')
for item in glass:
for i in range(sheet1.nrows):
if sheet1.cell_value(i,0)==glass:
reversed_transmission=sheet1.row_values(i,37,67)
transm_index=reversed_transmission[::-1]
new_transm_index=[float(ni) for ni in transm_index ]
wavel_range=sheet1.row_values(3,37,67)
temp_wavel= [k.split('/')[1] for k in wavel_range]
wRange=map(int,temp_wavel[::-1])
plt.plot(wRange,new_transm_index, 'r-')
plt.grid(True, which="both")
plt.show()
return new_transm_index, wRange
if __name__=='__main__':
new_transm_index=transmittance('N-BASF64','N-BK7')
print 'get tuple length and glass name: ' ,new_transm_index
我无法重现您在问题中描述的TypeError(如果在没有任何参数的情况下调用
transmission()
,我可能会得到)。然而,当使用与我在谷歌上找到的同名XLS文件调用函数时,我却遇到了两个不同的错误
- 迭代
,然后与整个列表进行比较,而不是与当前的玻璃中的项目
项目
- 创建
列表时,不能仅强制转换为new\u transm\u index
,因为表中有一些空字符串;在这种情况下,我假设值为零float
新的\u transm\u索引
保存glass
中每个项目的列表(如注释中所述),则应使用字典,将项目(键)映射到相应的列表(值)
如果为该语言添加标记,您可能会得到更多的响应。我编辑了空格,使其至少在语法上正确,但我不确定它是否正是您想要的,@Ivranovi--您可以查看它吗?另外,您能告诉我们如何调用
transmission
以及错误的全文是什么吗?我想为返回的参数检索一个“动态”列表数组,即不仅是最后一项,而且是allcool!太好了,非常感谢!有没有办法用不同的颜色自动绘制曲线?@Ivranovi当我测试它时,它确实用不同的颜色自动绘制曲线;一个是蓝色的,另一个是绿色的。这不是为了你的健康吗?
...
new_transm_index = {} # create dictionary
for item in glass:
for i in range(sheet1.nrows):
if sheet1.cell_value(i, 0) == item: # compare to item, not to list
...
# do not cast ' ' to float, but use 0 if not of type float
new_transm_index[item] = [ni if type(ni) == float else 0 for ni in transm_index]
...
for item in glass: # add plots for all items to common diagram
plt.plot(wRange,new_transm_index[item])
plt.grid(True, which="both")
plt.show()
...