对列表类变量执行映射操作

时间:2015-08-08 14:13:39

标签: python python-2.7 python-3.x ipython ipython-notebook

以下代码会返回错误:

init(reflecting:)
  

TypeError:'int'对象不可订阅

但是,如果要将逻辑与类分开 - 它按预期工作

extension String {
    /// Initialize `self` with the textual representation of `instance`.
    ///
    /// * If `T` conforms to `Streamable`, the result is obtained by
    ///   calling `instance.writeTo(s)` on an empty string s.
    /// * Otherwise, if `T` conforms to `CustomStringConvertible`, the
    ///   result is `instance`'s `description`
    /// * Otherwise, if `T` conforms to `CustomDebugStringConvertible`,
    ///   the result is `instance`'s `debugDescription`
    /// * Otherwise, an unspecified result is supplied automatically by
    ///   the Swift standard library.
    ///
    /// - SeeAlso: `String.init<T>(reflecting: T)`
    public init<T>(_ instance: T)

    /// Initialize `self` with a detailed textual representation of
    /// `subject`, suitable for debugging.
    ///
    /// * If `T` conforms to `CustomDebugStringConvertible`, the result
    ///   is `subject`'s `debugDescription`.
    ///
    /// * Otherwise, if `T` conforms to `CustomStringConvertible`, the result
    ///   is `subject`'s `description`.
    ///
    /// * Otherwise, if `T` conforms to `Streamable`, the result is
    ///   obtained by calling `subject.writeTo(s)` on an empty string s.
    ///
    /// * Otherwise, an unspecified result is supplied automatically by
    ///   the Swift standard library.
    ///
    /// - SeeAlso: `String.init<T>(T)`
    public init<T>(reflecting subject: T)
}
  

[1,3]

可以请任何人解释为什么对类变量执行相同的操作会导致上述错误吗?

P.S。我正在使用python 3.4,虽然不认为它很重要

1 个答案:

答案 0 :(得分:2)

如果您实际使用属性self.l

,则代码可以正常运行
    def funct(self):
        self.l  = list(map(lambda x: x[0], self.l))
        print(self.l)

输出:

[1, 3]

在某个地方,你在某个l或者在self.l中定义了一个int,如果没有定义l,你会得到一个`UnboundLocalError:local variable&#39; l&#39 ;在转让前引用。

根据您的评论,这是一个拼写错误,那么int中的self.l不仅仅是元组:

class my_class:
    def __init__(self):
        self.l = [3,(1,2),(3,4)]

    def funct(self):
        l  = list(map(lambda x: x[0],self.l))
        print(self.l)

然后运行示例:

In [2]: ob = my_class()

In [3]: ob.funct()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-e9ee341f0f31> in <module>()
----> 1 ob.funct()

<ipython-input-1-e1a6b2682f9f> in funct(self)
      4 
      5        def funct(self):
----> 6            l  = list(map(lambda x: x[0],self.l))
      7            print(self.l)

<ipython-input-1-e1a6b2682f9f> in <lambda>(x)
      4 
      5        def funct(self):
----> 6            l  = list(map(lambda x: x[0],self.l))
      7            print(self.l)

TypeError: 'int' object is not subscriptable

`