python-3.x - 当 python2 语句不再起作用时,在 python3 中打印一个 dict
问题描述
我的python2程序中有以下打印语句(在'-'符号之后)并用一些更复杂的python3代码(在'+'符号之后)替换它。有没有更好的更优雅的方式来做到这一点?
- print("%(txn_processed)8d %(txn_skip)5d %(txn_ctr)5d")%accounts[account]
+ acc_ctrs = accounts[account]
+ processed = accounts[account]['txn_processed']
+ skipped = accounts[account]['txn_skip']
+ ctr = accounts[account]['txn_ctr']
+ print('%8d %5d %5d'%(processed, skipped, ctr))
字典帐户每个帐户有一个条目,子字典中有 3 个计数器。所以我在一个for account in accounts:
循环中处理帐户并将 3 个计数器分为已处理、跳过和求和。这就是输出的样子(特别是最后两行):
Output to ofx (GnuCash version)
TRANSACTIONS: 248
IN: 2018-008-transactions-30-12-to-26-09.csv
OUT: 2018-008-transactions-30-12-to-26-09.ofx
accountnumber processed skip sum
NL89RABO0000000000 231 0 231
NL71RABO1111111111 1 16 17
我对python3的了解有限。希望你们能帮帮我。
PS python2 行返回了关于 NoneType 和 Dict 的错误消息。
亲切的问候,古斯。
解决方案
print
是 python 3 中的一个函数,但你有混淆括号:
Python 2 的解释如下:
print ("%(txn_processed)8d %(txn_skip)5d %(txn_ctr)5d") % accounts[account]
# ^----------------------- argument to print ---------------------------------------^
事实上,这些围绕字符串的括号在 python 2 中是完全不需要的。
Python 3 的解释是将括号视为参数,就像任何常规函数/方法一样:
print ("%(txn_processed)8d %(txn_skip)5d %(txn_ctr)5d") % accounts[account]
# ^------------- argument to print --------------^
并print
返回None
,您正试图调用__rem__
它。这就是你有错误的原因。
为 Python 3 修复它所需要做的就是将所有内容都包含在括号中,而不仅仅是将要格式化的字符串:
print("%(txn_processed)8d %(txn_skip)5d %(txn_ctr)5d" % accounts[account])
# ^------------- argument to print ---------------------------------^
推荐阅读
- ios - 委托总是在动态框架类中获得零值
- wordpress - 从functions.php短代码调用类函数
- ruby-on-rails - 将附加字段动态添加到 rails 表单
- visual-studio-code - VS 代码自动补全自定义
- javascript - Chart.js 无法读取未定义的属性“fontSize”
- google-analytics - 如何将 Google Analytics(分析)自定义维度设置为数据洞察报告中的维度过滤器?
- forms - 如何在 xamarin 表单的一个内容页面上添加多个选项卡式页面?
- ios - 扩展应用程序和主机应用程序之间的 React-native 通信
- python - OpenCV 断言以负值失败
- django - 每个列表的图片无限制