gpt4 book ai didi

python三元if语句没有捕获None

转载 作者:行者123 更新时间:2023-12-05 00:50:48 26 4
gpt4 key购买 nike

我正在实现从 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 时是否遗漏了什么? ?
谢谢!

最佳答案

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

这个:

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

可能是 pointer1是 None,因此没有 data属性,这就是您收到异常的原因。所以你需要检查 pointer1不是 None访问前 data .

关于python三元if语句没有捕获None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45442524/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com