python - Python IDE 自动重构重复代码
问题描述
假设我正在编写一系列命令并决定将其转换为 for 循环。例如说我有
print('Jane','Bennet')
print('Elizabeth','Bennet')
print('Mary','Bennet')
首先,我决定把它变成一个 for 循环:
for s in ['Jane','Elizabeth','Mary']:
print(s,'Bennet')
甚至可能是列表理解:
[print(s,'Bennet') for s in ['Jane','Elizabeth','Mary']]
是否有可以在这些形式之间自动转换的 Python IDE?或者也许还有其他工具可以做到这一点?
解决方案
我不推荐列表理解重构。由于列表推导式严格地用作迭代生成列表的简明符号,因此更难阅读。如果您的编辑器具有矩形选择功能,您可以这样做:
# First tab the sirnames out away from the given names. (They don't need to be neatly
# aligned like this, you can just copy paste a bunch of spaces.)
print('Jane', 'Bennet')
print('Elizabeth', 'Bennet')
print('Mary', 'Bennet')
# Use rectangular selection to get rid of the sir names and the print statements,
# leaving the commas. An editor like Geany will also allow you to get rid of the
# trailing whitespace, making your code easier to navigate.
'Jane',
'Elizabeth',
'Mary',
# Add a variable initialization followed by square brackets around the given names.
# You can also pretty it up by indenting or deleting newlines as you see fit.
givenNames = [
'Jane',
'Elizabeth',
'Mary',
]
# Add your for loop.
givenNames = [
'Jane',
'Elizabeth',
'Mary',
]
for name in givenNames:
print(f"{name} bennet")
推荐阅读
- c# - ASCII 编码 - 一个有效,另一个抛出错误消息 - “消息:输入字符串格式不正确”
- mysql - 来自两个表的 Sql Case 语句
- css - CSS 网格,网格项“高度:100%”在 Chrome 中不起作用
- docker - docker 容器退出状态 255 是什么意思?
- java - 多个 UI 元素从一个表到一个数组
- apache - 阻止 .htaccess 中的特定 URL
- owasp - 使用 OWASP ZAP 的 ZEST 脚本身份验证
- lilypond - 这个 Lilypond 警告是什么:“找不到可行的初始配置:可能找不到好的光束斜率”?
- matlab - 查找给定总和的 -1 和 1 的所有组合
- c# - WPF:MVVM上的窗口之间的通信