python三元if语句没有捕获无

时间:2017-08-01 15:58:09

标签: python if-statement ternary-operator

我正在实现在python中从两个链表中添加两个数字的算法。 (从破解编码面试2-5)

例如,

first: 7 -> 1 -> 6      617
second: 5 -> 9 -> 2    +295
                       -----
                        912
output: 2 -> 1 -> 9 ( which indicates 912 )

这是我的代码,

class Node:
    def __init__(self, val=None):
        self.data = val
        self.Next = None

class LinkedList:
    def __init__(self):
        self.head = None
        self.size = 0

    def __repr__(self):
        temp = self.head
        alist = []
        while temp:
            alist.append(temp.data)
            temp = temp.Next
        return str(alist)

    def add(self, val):
        cur = self.head
        prev = None
        if cur is None:
            self.head = Node(val)
        else:
            while cur:
                prev = cur
                cur = cur.Next
            prev.Next = Node(val)
        self.size += 1

def adding(p1,p2):
    pointer1 = p1.head
    pointer2 = p2.head
    remainder = 0
    sum_list = LinkedList()

    while pointer1 is not None or pointer2 is not None:
        first = 0 if pointer1.data is None else pointer1.data
        second = 0 if pointer2.data is None else pointer2.data
        sum_ = first + second + remainder

        remainder = 1 if sum_ >= 10 else 0

        sum_ %= 10

        sum_list.add(sum_)

        if pointer1 is not None:
            pointer1 = pointer1.Next
        if pointer2 is not None:
            pointer2 = pointer2.Next
    if remainder > 0:
        sum_list.add(remainder)
    return sum_list

我的问题是first = 0 if pointer1.data is None else pointer1.data。 当两个链接列表的大小相同时它正在工作,但是,如果一个比其他链接列表短,则较短的一个变为None。所以我希望我的if语句捕获这个并使变量(第一个)成为0。但是它会抛出AttributeError: NoneType object has no attribute 'data'

如果我正常写,而不是ternary operator

,它会工作
if pointer1 is None:
    first = 0
else:
    first = pointer1.data
if pointer2 is None:
    second = 0
else:
    second = pointer2.data

我使用ternary operator时是否遗漏了什么? 谢谢!

2 个答案:

答案 0 :(得分:2)

是的,您实际上并没有执行if / else语句对三元运算符的操作。

此:

template = Templates().get_template(url) # assume returns Dealer()
template.url
# 'http://www.some-website.com'
template.response.status_code
# 200

将是以下内容:

if pointer1 is None:
    first = 0
else:
    first = pointer1.data
if pointer2 is None:
    second = 0
else:
    second = pointer2.data

在您的版本中:

first = 0 if pointer1 is None else pointer1.data
second = 0 if pointer2 is None else pointer2.data

first = 0 if pointer1.data is None else pointer1.data 可能是None,因此没有pointer1属性,这就是您获得异常的原因。因此,在访问data之前,您需要检查pointer1是否不是None

答案 1 :(得分:1)

问题是您正在检查df.withColumn("word_check", dict.foldLeft(lit(false))((a, b) => a || locate(b, $"words") > 0)).show +---+------+----------+ | id| words|word_check| +---+------+----------+ | 1| foo| true| | 2|barrio| true| | 3|gitten| false| | 4| baa| false| +---+------+----------+ 是否为无。但它实际上是pointer.data,它将是None,所以当你的代码到达三元组时,它将首先尝试从None对象获取属性pointer

您需要更改代码,以便检查data是否为无:pointer