繁体   English   中英

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

[英]Why is my function returning None instead of my key values

我想做一个返回相邻位置元组的 function 。 但我无法返回字典值。

我的代码:

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

output 应该是:

>>>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')

问题是当我运行我的 function 时,会发生这种情况:

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

(None, None, None)

而不是我的关键价值观。

字典中的键是字符串,但您的代码尝试查找“位置”,我假设它是 object。

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

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

或者让 function 自己做:

adjacents = adj[position_to_str(p)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM