我试图在Python中将一个包含5个列表的元组打印到一个文件中,但是,我得到了错误:
TypeError: Can't convert 'tuple' object to str implicitly
以下是我的代码:
def listjoin(): illegallist = zip(carreglist, illegalspeed, illegaltime, illegalname, illegaladdress) for item in illegallist: illegaldatafile.write("Registration: "+item) illegaldatafile.write("\n") illegaldatafile.write("Speed "+item) illegaldatafile.write("\n") illegaldatafile.write("Time: "+item) illegaldatafile.write("\n") illegaldatafile.write("Name: "+item) illegaldatafile.write("\n") illegaldatafile.write("Address: "+item) illegaldatafile.write("\n") illegaldatafile.write("\n") illegaldatafile.close()
我想要得到这样的东西:
Registration: BH34JKX Speed: 80 Time: 6:45:21 Name: John Adams Address: SW34 7MN Registration: DX34JKS
等.(意外发布太早)
我在代码中先前打印了一个列表到文件,并且不需要将其转换为字符串.我不能这样做:
illegallist = zip(str(carreglist, illegalspeed, illegaltime, illegalname, illegaladdress))
因为str()只需要3个参数.我试过把它放在这里:
illegallist = str(zip(carreglist, illegalspeed, illegaltime, illegalname, illegaladdress))
但后来它只是说我的文件已关闭.
您将相同的元组item
一遍又一遍地添加到字符串中.你必须从这个元组中获取单个元素.这是我的(更紧凑)提案:
colnames = ['Registration', 'Speed', 'Time', 'Name', 'Address'] for tup in zip(carreglist, illegalspeed, illegaltime, illegalname, illegaladdress): for colname, value in zip(colnames, tup): illegaldatafile.write('{}: {}\n'.format(colname, value)) illegaldatafile.write('\n')
而不是简单地调用每个循环迭代的项目item
,您应该解压缩它,以便您可以更轻松地引用每个对象.字符串格式也很有用:
def listjoin(): illegallist = zip(carreglist, illegalspeed, illegaltime, illegalname, illegaladdress) for reg,speed,timing,name,address in illegallist: illegaldatafile.write("Registration: {}\n".format(reg)) illegaldatafile.write("Speed: {}\n".format(speed)) illegaldatafile.write("Time: {}\n".format(timing)) illegaldatafile.write("Name: {}\n".format(name)) illegaldatafile.write("Address: {}\n\n".format(address)) illegaldatafile.close()