Skip to main content
 首页 » 编程设计

python之一个衬垫加高

2025年05月04日19hnrainll

如果可能的话,我怎么能把它放在一行上呢?

a = [int(i) if i.isdigit() else raise DnDException("%s is not a number."% i) for i in list_of_strings]

我希望它执行以下操作:

a = [] 
for i in list_of_strings: 
    if i.isdigit(): 
        a.append(int(i)) 
    else: 
        raise DnDException("%s is not a number." % i)  

请您参考如下方法:

技术上可能单线:

[int(i) if i.isdigit() else (_ for _ in ()).throw(DnDException("%s is not a number." % i)) for i in list_of_strings] 

不过不要告诉任何人你是从我这里听到的。

改为这样做,更具可读性:

def func(i): 
    if i.isdigit(): 
        return int(i) 
    raise DnDException("%s is not a number." % i)  
 
a = [func(i) for i in list_of_strings] 

注意:注意负数,字符串 "-2"将返回 False对于 str.isdigit .