TypeError:“间隔”对象不可迭代

我喜欢巧克力
# Definition for an interval.
# class Interval:
#     def __init__(self, s=0, e=0):
#         self.start = s
#         self.end = e

class Solution:
    def merge(self, intervals):
        """
        :type intervals: List[Interval]
        :rtype: List[Interval]
        """

        out = []  
        for i in sorted(intervals, key=lambda i: i.start):
            if out and i.start <= out[-1].end:
                out[-1].end = max(out[-1].end, i.end)
            else:
                out += i
        return out

对于第二行,出+ = i,我收到此错误:
'Interval'对象不可迭代。

我相信添加逗号后会起作用:

出+ =我,

但我不知道为什么,有人可以解释吗?

凯尔伍德

如果要将单个项目添加到列表的末尾,通常使用append

out.append(i)

您还可以使用添加可迭代项或元素序列(例如列表和元组)来扩展列表+=

i不是序列,因此out += i不起作用。

但是i,是一个序列。它是一个包含的元组i

所以

out += i,

确实有效。就像你写的一样

out += (i,)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章