Python IDE自动重构重复代码

问题描述 投票:0回答:1

假设我正在编写一系列命令,并决定将其转换为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?也许还有其他工具可以做到这一点?

python ide abstraction code-duplication
1个回答
0
投票

我不建议使用列表理解重构。很难理解,因为列表推导严格意为迭代生成列表的简明表示法。如果您的编辑器具有矩形选择功能,则可以执行以下操作:

# 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")
© www.soinside.com 2019 - 2024. All rights reserved.