Python Koans 单例元组

标签 python

我在通过 Greg Malcolm 的 Python Koans 的单例元组测试之一“test_tuples_of_one_look_peculiar”时遇到困难 ( https://github.com/gregmalcolm/python_koans/blob/master/python3/koans/about_tuples.py )。

具体来说,这是我提出(或在搜索中找到)的唯一答案

self.assertEqual(__, ("我是一个元组",))

是同义反复的 self 引用:

self.assertEqual(("我是一个元组",), ("我是一个元组",)) 这使得测试的学习或目的变得毫无意义。是的,x==x。

答案是否像 Python Zen 的 TOOWTDI 一样简单,或者还有另一个与单例元组构造函数等价的东西,(value,)

最佳答案

这似乎是一个没有提供任何信息的练习,因为有很多方法可以编写单例元组的创建。例如:

tuple(["I'm a tuple"])
tuple({"I'm a tuple"})
# ... etc. for other sequence types

("I'm a tuple",)

# or even
def single_value():
    yield "I'm a tuple"

tuple(value for value in single_value())

# or something ludicrous
next(map(tuple, [["I'm a tuple"]]))

或者甚至是像这样疯狂的犯罪想法:

In [43]: class TuplePiper(object):
    ...:     def __init__(self, value):
    ...:         self.value = value
    ...:
    ...:     def __rshift__(self, other):
    ...:         return other([self.value])
    ...:     

In [44]: TuplePiper("I'm a tuple") >> tuple
Out[44]: ("I'm a tuple",)

除非练习附带一个确定的假设或约束来解释这些可能性中的哪一个应该满足测试,否则这似乎只是一个偏好问题。

关于Python Koans 单例元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49888090/

相关文章:

python - python中的常量?

python - Pandas 每日 groupby 条件基于第一个更高的值

python - 光滑XMPP : Getting presence ['muc' ] ['jid' ] to message handler for each message

python Pandas : mean and sum groupby on different columns at the same time

python - 通过ORM删除多个Django对象

python - 值错误 : array is too big

python - Django 中 null=True 和 Blank=True 有什么区别?

python - discord.ext.commands.errors.CommandInvokeError : Command raised an exception: AttributeError: 'NoneType' object has no attribute 'qualified_name'

python - 在 Python 中使用 Paramiko ssh 到 ftp 服务器

用 python 编写的类似 Javascript 的 TCP 套接字客户端?