【发布时间】:2021-01-04 11:43:23
【问题描述】:
我想创建一个返回相邻位置元组的函数。但我无法返回字典值。
我的代码:
def creat_position(c,r):
if isinstance(c, str) and c in ('a', 'b', 'c') and isinstance(r, str) and l in ('1', '2', '3'):
return c, r
def position_to_str(pos):
c = str(obtain_pos_c(pos))
r = str(obtain_pos_r(pos))
if its_position(pos):
return c + r
def obtain_adjacent_positions(pos):
"""
obtain_adjacent_positions: position -> tuple of positions
"""
p = position_to_str(pos)
#'b''2' -> 'b2'
adj = {'a1': ('b1', 'a2'),
'b1': ('a1', 'b2', 'c1'),
'c1': ('b1', 'c2'),
'a2': ('a1', 'b2', 'a3'),
'b2': ('b1', 'a2', 'c2', 'b3'),
'c2': ('c1', 'b2', 'c3'),
'a3': ('a2', 'b3'),
'b3': ('b2', 'a3', 'c3'),
'c3': ('c2', 'b3')
}
adjacents = adj[p]
return adjacent
输出应该是:
>>>p1 = creat_positon('c', '1')
>>>p2 = creat_positon('b', '3')
>>>position_to_str(p2)
'b3'
>>>tuple(position_to_str(p) for p in obtain_adjacent_positions(p1))
('b1', 'c2')
>>>tuple(position_to_str(p) for p in obtain_adjacent_positions(p2))
('b2', 'a3', 'c3')
问题是当我运行我的函数时会发生这种情况:
>>>tuple(position_to_str(p) for p in obtain_adjacent_positions(p2))
(None, None, None)
而不是我的关键值。
【问题讨论】:
-
用你自己的话来说,当你做
position_to_str(p2)的时候,你期望p2的值改变吗?如何?为什么? -
我添加了更多代码来帮助理解函数。它可以改变,这取决于我在我的 creat_position(pos) 上设置的值
-
只看一眼你的代码,你就有
if its_position(pos):....如果不是那怎么办?然后它将返回None -
这里没有那个功能。返回一个布尔值,真或假。
-
请阅读ericlippert.com/2014/03/05/how-to-debug-small-programs并仔细追踪您的代码。例如,尝试在尝试获取
adj[p]之前立即检查p等于什么。这是你所期望的吗?如果不是,那就退后一步,试着解释一下。
标签: python dictionary key key-value-store