当前位置:  开发笔记 > 编程语言 > 正文

Python:无法将5个列表的元组打印到文件中

如何解决《Python:无法将5个列表的元组打印到文件中》经验,为你挑选了2个好方法。

我试图在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))

但后来它只是说我的文件已关闭.



1> eumiro..:

您将相同的元组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')



2> TigerhawkT3..:

而不是简单地调用每个循环迭代的项目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()

推荐阅读
家具销售_903
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有