我有一个功能:
def save(self, text, *index):
file.write(text + '\nResults:\n')
if index == (): index = (range(len(self.drinkList)))
for x in index:
for y in self.drinkList[x].ing:
file.write('min: ' + str(y.min) + ' max: ' + str(y.max) + ' value: ' + str(y.perc) + '\n')
file.write('\n\n')
file.write('\nPopulation fitness: ' + str(self.calculatePopulationFitness()) + '\n\n----------------------------------------------\n\n')
Run Code Online (Sandbox Code Playgroud)
现在,当我传递一个参数作为索引时,函数按原样运行,但是当我传递2个索引的元组时,我得到一个TypeError:list indices必须是整数,而不是元组.我应该改变什么?
该save(self, text, *index)语法意味着,index本身就是一个元组与传递给所有参数save的后text一个.
所以,例如,如果你的代码中有:
myobject.save("sample text", 1, 2, 3)
Run Code Online (Sandbox Code Playgroud)
然后index将元组(1, 2, 3)和for x in
index超过值将正常循环1,2,3.
另一方面,如果你有L
myobject.save("sample text", (1,2))
Run Code Online (Sandbox Code Playgroud)
然后index将是1元素元组((1,2),),并且x在循环中将得到值(1,2),因此TypeError.