我正在开发一个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 (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_longest
的 fillvalue
关键字参数:
ziplongest(..., ..., fillvalue=('', ''))
否则,默认值为 None
且 None
无法填充 2 元组,例如 (username, usrValue)
。
除此之外,由于字典没有排序,zip
操作将返回随机对...
关于python - 类型错误 : 'NoneType' object is not iterable when using zip_longest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50642650/