Skip to main content
 首页 » 编程设计

python之缩短循环以使用多个 for 和 ifs/elifs 列出理解

2024年10月17日8lyj

我有这段代码,其中字典键是函数,值是包含关键字的列表。它搜索列出的 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 for 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] 

但是,我无法将当前代码转换为类似列表理解的代码。

请您参考如下方法:

正如评论中所解释的那样,在这里使用列表理解没有任何好处。它实际上会更慢,因为您将创建一个您实际上并不想要的列表。此外,纯粹出于副作用而使用列表组合被认为是糟糕的设计。

正如我在评论中提到的,您的字典设计是错误的方式,因此您无法获得使用字典的好处,即字典可以快速测试键是否存在,并且可以快速检索与键关联的值。

假设您当前的代码可以满足您的需求,这里有一种更好的编写方法。

def do_this(): 
    print 'Do This!\n' 
 
def do_that(): 
    print 'Do That!\n' 
 
def now_this(): 
    print 'Now This!\n' 
 
dct = { 
    'hi': do_this, 
    'hello':  do_this, 
    'bye': do_that, 
    'goodbye': do_that, 
} 
 
data = ('hi there', 'python', 'goodbye hello', '') 
for t in data: 
    v = t.split(None, 1)[0] if t else '' 
    print [t, v] 
    dct.get(v, now_this)() 

输出

['hi there', 'hi'] 
Do This! 
 
['python', 'python'] 
Now This! 
 
['goodbye hello', 'goodbye'] 
Do That! 
 
['', ''] 
Now This! 

这是没有 print 语句的 for 循环的更紧凑版本:

for t in data: 
    dct.get(t.split(None, 1)[0] if t else '', now_this)() 

我们使用条件表达式 (t.split(None, 1)[0] if t else '') 因此当 t 为空字符串时我们可以处理.这是一个可读性较差的替代版本。 :)

for t in data: 
    dct.get((t.split(None, 1) or [''])[0], now_this)() 

如果您可以保证 t 永远不会是空字符串,那么您可以使用简单版本:

for t in data: 
    dct.get(t.split(None, 1)[0], now_this)()