Python 类型错误:';非类型';对象在使用zip时不可编辑
我正在开发一个python脚本来分析txt文件,然后将其保存到osv文件中。我试图使用模块“itertools”中的“zip_longest”。当我的一个字典不再具有i值时,我希望它粘贴一个空白,而另一个字典继续粘贴其值。 我的代码如下所示:Python 类型错误:';非类型';对象在使用zip时不可编辑,python,python-3.x,Python,Python 3.x,我正在开发一个python脚本来分析txt文件,然后将其保存到osv文件中。我试图使用模块“itertools”中的“zip_longest”。当我的一个字典不再具有i值时,我希望它粘贴一个空白,而另一个字典继续粘贴其值。 我的代码如下所示: def csvExport(self): exportYN = input("Would you like to export the document to a CSV file? (Y/N):") if (exportY
def csvExport(self):
exportYN = input("Would you like to export the document to a CSV file? (Y/N):")
if (exportYN == "Y" or exportYN == "y"):
with open('data.csv', 'w', encoding="utf-8") as csvfile:
csvfile.write("Username;Repeated;Password;Repeated")
for (username, usrValue), (password, passValue) in itertools.zip_longest(self.usernames.items(), self.passwords.items()):
csvfile.write(str(username) + ";" + str(usrValue) + ";" + str(password) + ";" + str(passValue))
for (username, usrValue), (password, passValue) in itertools.zip_longest(self.usernames.items(), self.passwords.items()):
TypeError: 'NoneType' object is not iterable
错误代码如下所示:
def csvExport(self):
exportYN = input("Would you like to export the document to a CSV file? (Y/N):")
if (exportYN == "Y" or exportYN == "y"):
with open('data.csv', 'w', encoding="utf-8") as csvfile:
csvfile.write("Username;Repeated;Password;Repeated")
for (username, usrValue), (password, passValue) in itertools.zip_longest(self.usernames.items(), self.passwords.items()):
csvfile.write(str(username) + ";" + str(usrValue) + ";" + str(password) + ";" + str(passValue))
for (username, usrValue), (password, passValue) in itertools.zip_longest(self.usernames.items(), self.passwords.items()):
TypeError: 'NoneType' object is not iterable
我认为这与zip_longest有关,因为我使用的两本字典的长度不一样
希望您能提供帮助:)您需要使用
zip\u longest
的fillvalue
关键字参数:
ziplongest(..., ..., fillvalue=('', ''))
否则,默认值为None
,并且None
无法填充2元组,例如(username,usrValue)
除此之外,由于字典没有排序,
zip
操作将返回随机对…字典的可能重复并不保证顺序(尽管从Python 3.6开始,输入顺序被保留);根据这些字典的生成方式,您可能无法获得所需的输出顺序。而NoneType
错误源于尝试将None
解包为两个变量,即username,usrValue=None
或password,passValue=None
。想想什么样的默认值而不是None
适合这种情况。