【问题标题】:Why is my function returning None instead of my key values为什么我的函数返回 None 而不是我的键值
【发布时间】: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


【解决方案1】:

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

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

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

或者让函数自己做:

adjacents = adj[position_to_str(p)]

【讨论】:

  • 好,第二种方法adjacents = adj[position_to_str(p)]比较实用。
  • 它仍然返回 (None, None,None) 而不是 ('b2', 'a3', 'c3')。当我打印时(adjacents = adj[position_to_str(pos)]) 它给了我值,但是有了这个 'TypeError: 'NoneType' object is not iterable'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-03
  • 1970-01-01
  • 2020-10-17
  • 2021-11-13
相关资源
最近更新 更多