gpt4 book ai didi

Python:在 "lambda"内定义变量

转载 作者:行者123 更新时间:2023-12-01 05:02:12 25 4
gpt4 key购买 nike

所以,我尝试在这里搜索,但找不到该问题的任何解决方案:我需要在“lambda”内定义一个变量。

我有那段代码:

def z(t,s):exec("t=s")
r = type('', (), {
'__init__': lambda t,*s: z("t.c",s),
's': lambda t: (lambda t,*s: [t[::-1] for t in s])(*t.c),
'l': lambda t: (lambda t,*s: list(s[::-1]))(*t.c),
'd': lambda t: t.c
})

w = ["APPLE", "BEACH", "CITRUS"]
print r(*w).s()
print r(*w).l()
print r(*w).d()

没有任何东西能正常工作...此外,当我调用函数“d”时,它会返回此错误:

AttributeError: '' object has no attribute 'c'

When it should return a tuple, something like:

('ALPHA', 'BRAVO', 'CHARLIE')

EDIT: Thanks guys, it works now, and is even smaller:

r=type('',(),{'__init__':lambda t,*s:setattr(t,'c',s),'s':lambda t:[t[::-1] for t in t.c],'l':lambda t:list(t.c[::-1]),'d':lambda t:t.c})

最佳答案

您需要使用setattr设置属性:(如果您想要类似 self.c = s 的内容)

'__init__': lambda t,*s: setattr(t, 'c', s),
<小时/>
>>> r = type('', (), {
... '__init__': lambda t,*s: setattr(t, 'c', s),
... 's': lambda t: (lambda t,*s: [t[::-1] for t in s])(*t.c),
... 'l': lambda t: (lambda t,*s: list(s[::-1]))(*t.c),
... 'd': lambda t: t.c
... })
>>>
>>> w = ["APPLE", "BEACH", "CITRUS"]
>>> print r(*w).s()
['HCAEB', 'SURTIC']
>>> print r(*w).l()
['CITRUS', 'BEACH']
>>> print r(*w).d()
('APPLE', 'BEACH', 'CITRUS')

关于Python:在 "lambda"内定义变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25830004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com