【问题标题】:Python IDE to auto-refactor duplicate codePython IDE 自动重构重复代码
【发布时间】:2019-12-08 16:39:12
【问题描述】:

假设我正在编写一系列命令,并决定将其转换为 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 可以自动在这些形式之间进行转换?或者也许有其他工具可以做到这一点?

【问题讨论】:

  • 另一方面,这个列表理解将构建一个None 的列表。您应该使用推导来构建列表,而不是用于在内部调用的函数的副作用 - 在正常循环中更好地表达。
  • 我相信你可以在大多数编辑器中找到一种方法来做这样的事情,尽管它可能需要脚本/插件/等。这真的有那么大的问题吗?
  • 现有 IDE 的脚本或插件非常适合我的需求。
  • 好的,显示的列表理解是一个不好的例子。更好的方法是将[f('Jane','Bennet'), f('Elizabeth','Bennet'), f('Mary','Bennet')] 转换为[f(s,'Bennet') for s in ['Jane','Elizabeth','Mary']]

标签: python ide abstraction code-duplication


【解决方案1】:

我不推荐列表理解重构。由于列表推导式严格地用作迭代生成列表的简明符号,因此更难阅读。如果您的编辑器具有矩形选择功能,您可以这样做:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-30
    • 2010-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多