python - 类型错误 : 'NoneType' object is not iterable when using zip_longest

标签 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 (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_longestfillvalue 关键字参数:

ziplongest(..., ..., fillvalue=('', ''))

否则,默认值为 NoneNone 无法填充 2 元组,例如 (username, usrValue)

除此之外,由于字典没有排序,zip 操作将返回随机对...

关于python - 类型错误 : 'NoneType' object is not iterable when using zip_longest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50642650/

相关文章:

python - numpy meshgrid 过滤掉点

python - 主管中的多个程序

python - 重复列表中的每个元素任意次

python - 使用 Python 3 进行 Asyncore 数据处理

python - 如何获取我的模型所附加的 session ID?

python - 使用 Logbook 和 ZeroMQ,为什么我需要等待才能传递消息?

python - 字符串到字典字数统计

python - 如何获取特定时区的当前时间?

Django数据库根据当前登录用户进行路由

python - 统计调查结果