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','Mary']]

是否存在可以自动在这些表单之间转换的Python IDE?也许还有其他工具可以做到这一点?

beibeiji 回答: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',]
# Add your for loop.
givenNames = [
  'Jane',]
for name in givenNames:
    print(f"{name} bennet")
本文链接:https://www.f2er.com/2953083.html

大家都在问