我可以调用函数列表并使用列表理解吗?
def func1():return 1
def func2():return 2
def func3():return 3
fl = [func1,func2,func3]
fl[0]()
fl[1]()
fl[2]()
Run Code Online (Sandbox Code Playgroud)
我知道我能做到
for f in fl:
f()
Run Code Online (Sandbox Code Playgroud)
但我可以在下面做吗?
[f() for f in fl]
Run Code Online (Sandbox Code Playgroud)
例如,如果我的职能列表在课堂上,那么对于那些善良的人来说是另一个问题
class F:
def __init__(self):
self.a, self.b, self.c = 0,0,0
def func1(self):
self.a += 1
def func2(self):
self.b += 1
def func3(self):
self.c += 1
fl = [func1,func2,func3]
fobj= F()
for f in fobj.fl:
f()
Run Code Online (Sandbox Code Playgroud)
它有用吗?
对于以下代码
a =func()
if a != None:
b.append(a)
Run Code Online (Sandbox Code Playgroud)
a可以分配给None,有没有办法避免if语句只使用一行代码?
原始问题如下
import xml.etree.ElementTree as etree
r = etree.parse(f).getroot()
b = etree.Element('register',{})
a = r.find('tag_name') # a may get None if did not find it
if a != None:
b.append(a)
Run Code Online (Sandbox Code Playgroud)
好吧,我用了所有的答案并得到了这个,我个人认为这是迄今为止我写过的最复杂的python,哈哈,哈哈
NS_MAP = {
'spirit' : 'http://www.spiritconsortium.org/XMLSchema/SPIRIT/1.4',
'app' : 'http://www.app.com/SPIRIT-app'
}
mp=etree.Element('MemoryProperty', {'version':'alpha'})
mpt=etree.ElementTree(mp)
def copy_tags(tp, op, p, tn, ns='spirit'):
c = p.find('{%s}%s'%(NS_MAP[ns],tn))
if c is not None:
(op == '<-') and tp.append(c)
return c
for reg in regs:
te = etree.Element('register',{}) …Run Code Online (Sandbox Code Playgroud) 我记得我曾经见过一个能够在python中分解列表的运算符.
例如
[[1],[2],[3]]
Run Code Online (Sandbox Code Playgroud)
通过应用该运营商,你得到
[1], [2], [3]
Run Code Online (Sandbox Code Playgroud)
什么是该运营商,任何帮助将不胜感激.
我一直在尝试使用list comprehension在python中生成lambda函数列表.但它不起作用,
例如
fl=[lambda x: x**i for i in range(5)]
Run Code Online (Sandbox Code Playgroud)
我检查了另一个问题,它基本上根据i的引用生成相同的函数.
所以我也试过偏.
from functools import partial
fl=[partial(lambda x: x**i) for i in range(5)]
Run Code Online (Sandbox Code Playgroud)
但它也没有用.任何帮助将不胜感激.欢呼声〜
python ×4
list ×3
function ×2
flow-control ×1
fold ×1
folding ×1
if-statement ×1
lambda ×1
operators ×1
vim ×1