如果可能的话,如何将其放在一行上?

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)

最佳答案

虽然@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]

关于python - 一类加薪类轮,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58550806/

10-12 13:06