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")

最新更新