我遇到的问题很难解释,很容易理解:
我有一个元组列表:
L=[('a','111'),('b','222'),('a','333'),('b','444')]
Run Code Online (Sandbox Code Playgroud)
从这个列表中,我想创建一个字典,其中键是元组的第一个元素('a' 和 'b'),关联的值在一个列表中:
预期输出:
{'a':['111','333'],'b':['222','444']}
Run Code Online (Sandbox Code Playgroud)
我怎么解决这个问题?
d={}
for x in range (len(L)):
d[L[x][0]]=[L[x][1]]
return d
Run Code Online (Sandbox Code Playgroud)
但正如您可以轻松理解的那样,输出将不完整,因为列表将仅显示与 L 中该键关联的最后一个值
我想编写一个函数来显示给定的树是否是 BinarySearch。
这是我到目前为止所写的:
class Node:
def _isBinary(self):
L=[]
if self.left is not None and self.right is not None:
if self.left.data>self.data or self.right.data<self.data:
L.append(1)
else:
L+=self.left._isBinary()
L+=self.right._isBinary()
else:
if self.left is not None:
if self.left.data>self.datat:
L.append(1)
else:
self.left._isBinary()
if self.right is not None:
if self.right.data<self.data:
L.append(1)
else:
self.right._isBinary()
return L
class tree:
def isBinary(self):
if self.root is None:
return
else:
return not 1 in self.root._isBinary(self.root.data)
Run Code Online (Sandbox Code Playgroud)
(顺便说一句,我刚刚报告了代码中感兴趣的部分)这段代码运行良好,但是当例如一个数字(大于根)在树的左侧,但它是较低的数字:
99
/ \
8 888
\
100
Run Code Online (Sandbox Code Playgroud)
它应该给我 False,而不是它返回 True。我能做什么?(如果可能,不完全改变我的原始代码?)