【问题标题】:Convert a function into a lambda将函数转换为 lambda
【发布时间】:2014-09-20 00:57:21
【问题描述】:

此代码检查系统是 Windows 还是 Linux,导入所需的库,并定义一个有效的“获取”函数。
但是...函数“_d”可以在 lambda 中完成吗?

def _d():
    import sys, tty, termios
    f = sys.stdin.fileno()
    o = termios.tcgetattr(f)
    try:
        tty.setraw(sys.stdin.fileno())
        c = sys.stdin.read(1)
    finally:
        termios.tcsetattr(f, termios.TCSADRAIN, o)
    return c

_u = type('', (), {
    '__init__': lambda s: setattr(s, '', (None for sys in [__import__('sys')] for tty in [__import__('tty')])),
    '__call__': _d()
})

_w = None if ImportError else __import__("msvcrt").getch()

getch = (type('', (), {
    '__init__': lambda s: setattr(s, 'i', _u()) if ImportError else setattr(s, 'i', _w()),
    '__call__': lambda s: s.i()
}))()


我目前有:

setattr(type('',(),{}), '', (
    None for sys in [__import__('sys')]
    for tty in [__import__('tty')]
    for termios in [__import__('termios')]
    for f in sys.stdin.fileno()
    for o in termios.tcgetattr(f)
    for _ in tty.setraw(sys.stdin.fileno())
    for c in sys.stdin.read(1)
    for _ in termios.tcsetattr(f, termios.TCSADRAIN, o)
))

但这并不能让我返回“c”。

【问题讨论】:

  • 哇...你到底为什么要这样做?此外,lambda s: _d() 应该只是 _d
  • 只是因为。 thx,在我更改“u.__call_”中的代码后,我错过了那个。
  • 这是一个非常非常糟糕的主意。钉子不适合孔,好吗?请停止试图把它塞进去。你会打破这该死的东西。
  • 无需将答案编辑到问题中。最好让问题成为问题,答案成为答案。
  • 顺便说一句,您无法使用if 语句捕获异常。

标签: python function class lambda getch


【解决方案1】:

好吧,如果你必须:

lambda: exec("""
def _d():
    import sys, tty, termios
    f = sys.stdin.fileno()
    o = termios.tcgetattr(f)
    try:
        tty.setraw(sys.stdin.fileno())
        c = sys.stdin.read(1)
    finally:
        termios.tcsetattr(f, termios.TCSADRAIN, o)
    return c
""", globals()) or _d()

它似乎比其他替代品更具可读性。


不过,要修复您给定的代码,请尝试:

lambda: next(
    c
    for sys in [__import__('sys')]
    for tty in [__import__('tty')]
    for termios in [__import__('termios')]
    for f in [sys.stdin.fileno()]
    for o in [termios.tcgetattr(f)]
    for _ in [tty.setraw(sys.stdin.fileno())]
    for c in [sys.stdin.read(1)]
    for _ in [termios.tcsetattr(f, termios.TCSADRAIN, o)]
)

【讨论】:

  • @WilliamFernandes 好吧,那么最好使用 Perl。在 Python 中 可读性很重要。
  • @AshwiniChaudhary 我试图让整个代码适合单个变量语句,以便在我的 Python 脚本中使用它。
猜你喜欢
  • 2016-03-02
  • 1970-01-01
  • 1970-01-01
  • 2022-11-24
  • 1970-01-01
  • 1970-01-01
  • 2018-10-29
  • 2018-06-15
  • 2019-10-20
相关资源
最近更新 更多