【问题标题】:How do I name a function that takes an object `A` and a set `{A, B}` as arguments, then returns `B`? [closed]如何命名以对象“A”和集合“{A,B}”为参数的函数,然后返回“B”? [关闭]
【发布时间】:2014-04-20 07:38:09
【问题描述】:

以下函数(在 Python 中实现)的好名字是什么?

def a_function(element, a_set):
    if a_set[0] == element:
        return a_set[1]
    if a_set[1] == element:
        return a_set[0]

assert 'A' == a_function('B', ['A', 'B'])

【问题讨论】:

  • 我的super_magical_awesome_comparison_and_validator_function(element, a_set)。只是在开玩笑。只需执行get_not 之类的操作
  • 怎么样a_set[not a_set.index(element)]:D
  • @hllau 你有一个小问题,Python 有一个 set,但这不是你使用的......我也会重命名参数。
  • @jonrsharpe:欢迎指正,虽然这不是问题的重点。
  • @hilau pair 相当中立,很容易表示,你不觉得吗?

标签: python function naming-conventions naming


【解决方案1】:

我会使用不同的函数名称、不同的参数名称和文档字符串来明确发生了什么,例如:

def get_other(current, both):
    """Return the element from 'both' that is not 'current'."""
    ...

请注意,both 表示一对没有任何冗长的内容,并且没有指定所需的 type

您可以使用自己的实现或 Joel 的实现;只要函数按照它所说的去做,它的实现方式并不重要(除非性能问题、边缘情况等)。

但是,如果要使用不可索引的容器(例如 set,或 dict 的键)而无需明确测试 both 是什么,我可能会选择:

def get_other(current, both):
    """Return the element from 'both' that is not 'current'."""
    for item in both:
        if item != current:
            return item

确实,如果 len(both) > 2,这将只返回其中不等于 current 的第一项 - 如果这不是所需的行为,您可以为此添加检查。

【讨论】:

  • 这符合 Python 的许多最佳实践。
【解决方案2】:

作为 jonrsharpe 建议的替代方案(我喜欢,不要误会我的意思),这是一个使用问题标题中提到的集合的单行版本:

>>> def get_other(element, pair):
...   """Get the other element from a pair"""
...   return (set(pair) - set([element])).pop()
... 

这会计算 elementpair 的集合差异,然后 pops 是结果集合中的一个随机成员(理想情况下应该是大小 1)。

以下是它处理不同可迭代数据类型的几个示例:

>>> get_other('B', {'A', 'B'})
'A'
>>> get_other('B', ['A', 'B'])
'A'
>>> get_other('A', ['A', 'B'])
'B'
>>> get_other('B', {'A': 1, 'B': 2})
'A'
>>> get_other('B', 'AB')
'A'
>>> get_other(5, {1, 5})
1

如果len(pair) > 2element not in pair,你返回的元素是未定义的,但总是来自pair 的元素:

>>> get_other('B', 'ABC')
'C'
>>> get_other('B', 'ABCDEF')
'E'

最后,如果pair 为空或pair == {element},则会引发KeyError

>>> get_other('B', 'B')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in get_other
KeyError: 'pop from an empty set'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    相关资源
    最近更新 更多