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

时间:2021-01-04 11:43:23

标签: 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_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)

而不是我的关键值。

1 个答案:

答案 0 :(得分:1)

字典中的键是字符串,但你的代码试图查找一个“位置”,我假设它是一个对象。

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

tuple(position_to_str(p) for p in obtain_adjacent_positions(position_to_str(p2)))

或者让函数自己做:

adjacents = adj[position_to_str(p)]
相关问题