【问题标题】:When iterating a list in a python loop, why is returned element a tuple? [closed]在 python 循环中迭代列表时,为什么返回的元素是一个元组? [关闭]
【发布时间】:2020-05-06 14:00:48
【问题描述】:

在遍历 python 列表中的元素时,我发现它返回的是单值元组,而不是基础值本身。我正在使用 Python 3.7.7 运行以下命令:

class MyClass:
    def __init__(self, value):
        """ class constructor """
        self.value = value,

    def __repr__(self):
        """ class repr method """
        return f'{self.__class__.__name__}(value={self.value!r})'

for val in [14, 20, 21, 48]:
    _myclass = MyClass(val)
    print(_myclass.value)

产生以下输出:

(14,)
(20,)
(21,)
(48,)

很明显,它将单元素元组传递给我的类构造函数,而不是列表中的基础值。当我将对象传递给 print 语句时,我可以看到相同的行为:

for val in [14, 20, 21, 48]:
    _myclass = MyClass(val)
    print(_myclass)

产生:

MyClass(value=(14,))
MyClass(value=(20,))
MyClass(value=(21,))
MyClass(value=(48,))

当我想在我的类中使用值时,这会成为一个问题——在这种情况下,将其视为预期的数字(例如,if value < 30: value = 30)会产生 TypeError。我该如何纠正这个问题?

【问题讨论】:

  • self.value = value, 逗号是元组构造函数,所以你说 self.value 是指包含值的元组
  • 写作value,(value,) 的简写,即单元素元组。
  • 噢!我现在看到了。我的菜鸟错误。谢谢!

标签: python list class iterator tuples


【解决方案1】:

您将, 放在self.value = value 附近删除它就可以了。 (有人在评论中提到)

class MyClass:
    def __init__(self, value):
        """ class constructor """
        self.value = value

    def __repr__(self):
        """ class repr method """
        return f'{self.__class__.__name__}(value={self.value!r})'

for val in [14, 20, 21, 48]:
    _myclass = MyClass(val)
    print(_myclass.value)
# output
# 14
# 20
# 21
# 48

【讨论】:

  • 似乎元组(self.value)是错误创建的。删除尾随逗号可能是一个更好的主意...
  • 是的我没看到很抱歉
  • 无害:只需更新或删除您的答案。
  • 是的,谢谢你
猜你喜欢
  • 2017-10-22
  • 1970-01-01
  • 1970-01-01
  • 2018-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 2019-09-05
相关资源
最近更新 更多