一个衬垫加高

one liner with raise

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

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" 将 return False for str.isdigit.

虽然正如@wim 所展示的那样技术上 是可行的,但编写如下内容更具可读性,它也适用于负数和十进制数。

try:
    a = list(map(int, list_of_strings))
except ValueError as e:
    raise DnDException(str(e))

更新:看来你也可以这样做:

class DnDException(Exception):
    def __init__(self, *args):
        super(DnDException, self).__init__(*args)
        raise self

list_of_strings = ["I", "will", "break", "this!", "7", "Haha!"]
a = [int(i) if str.isdigit(i) else DnDException("%s is not a number." % i) for i in list_of_strings]