【发布时间】:2016-11-06 22:44:48
【问题描述】:
我有这段代码,其中字典键是函数,值是包含关键字的列表。它搜索列出的t 并查看它是否在字典值的列表中。如果是,则运行该值的函数 [key]。如果没有,它将运行NowThis 函数。 count 变量就在那里,所以在这种情况下 t 是 'hello hi'。
dct = {doThis:['hi','hello'],
doThat:['bye','goodbye']}
t = 'hi there' # or 'test'|'goodbye'|'hello hi'
count=0
for listValue in t.split():
if count > 1 or count < 0:
break
elif listValue in [n for v in dct.values() for n in v]:
for key,vl in dct.iteritems():
if listValue in vl:
key()
count+=1
elif count==0:
nowThis()
count -=1
我确实有这个代码的以前版本,它只是用于 if 和 if,我很容易将其转换为列表理解:
[key() for listValue in t.split() if listValue in [n for v in dct.values() for n in v] for key,vl in dct.iteritems() if listValue in vl]
但是,我无法将当前代码转换为类似列表理解的代码。
【问题讨论】:
-
您确定要牺牲代码的可读性而不是复杂的列表理解吗?
-
如果你不使用
key的返回值,你不应该创建一个listcomp来执行循环。 -
我没有仔细查看您的代码,但字典看起来是从后到前的。你为什么不把'hi'、'hello'等字符串作为键,用你的函数作为值?
-
列表理解不会更快。列表推导的好处在于您可以使用裸表达式,其中
map需要将其包装在用户定义的函数中。比较[x['foo']['bar] for x in mylist]和map(lambda x: x['foo']['bar'], mylist)。 -
另外,您实际上并没有使用
for循环构建列表,因此列表推导式通过构建列表增加了更多开销。
标签: python list dictionary