Python 为什么我的函数返回None而不是键值

Python 为什么我的函数返回None而不是键值,python,dictionary,key,key-value-store,Python,Dictionary,Key,Key Value Store,我想做一个函数,返回相邻位置的元组。但是我很难返回字典中的值 我的代码: 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

我想做一个函数,返回相邻位置的元组。但是我很难返回字典中的值

我的代码:

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)

而不是我的键值。

字典中的键是字符串,但您的代码尝试查找“位置”,我假定它是一个对象

您可以将其作为字符串传递给函数:

tuple(position_to_str(p) for p in obtain_adjacent_positions(position_to_str(p2)))
或者让功能自行完成:

adjacents = adj[position_to_str(p)]

很好,第二个aproache
adjancets=adj[position\u to\u str(p)]
更实用。它仍然返回(None,None,None),而不是('b2','a3','c3')。当我打印(adjancets=adj[position\u to\u str(pos)]时,它会给我值,但是用你自己的话来说,这个“TypeError:“NoneType”对象是不可编辑的,当你做
position\u to\u str(p2)
时,你希望
p2
的值改变吗?怎样为什么?我添加了更多代码来帮助理解函数。它可以改变,这取决于我在我的创建位置(pos)上输入的值。只要看一下您的代码,您就有了
如果它的创建位置(pos):
。。。。如果不是那样呢?然后它将返回
None
这里没有该函数。返回布尔值,true或false。请仔细阅读并跟踪代码。例如,在尝试获取
adj[p]
之前,尝试检查
p
等于什么。这是你所期望的吗?如果没有,那就退后一步,试着解释一下。