如何在python构造函数中创建列表列表

时间:2018-05-17 07:52:31

标签: python class

我试图通过调用构造函数数组来创建使用类中不同函数的列表列表但是它给出了一个列表

我想专门使用build和build1这两个函数

class Sample:
   def __init__(self):
        self.add = list()

   def build(self,name):
        self.add.append(name)

   def build1(self,loc):
        self.add.append(loc)


s = Sample()
a1 = ["mohan,ps","gandhi,as"]
for a in a1:
    split_values = a.split(",")
    s.build(split_values[0])
    s.build1(split_values[1])

print s.add

输出

['mohan', 'ps', 'gandhi', 'as']

预期产出:

[['mohan', 'ps'],['gandhi', 'as']]

如何将结果作为预期输出

1 个答案:

答案 0 :(得分:0)

你可以试试这个。

class Sample:
   def __init__(self):
        self.add = list()

   def build(self,name):
        self.add.append(name)

   def build1(self,loc):
        self.add[-1].append(loc)     #Use negative index to append.


s = Sample()
a1 = ["mohan,ps","gandhi,as"]
for a in a1:
    split_values = a.split(",")
    s.build([split_values[0]])
    s.build1(split_values[1])

print s.add

<强>输出:

[['mohan', 'ps'], ['gandhi', 'as']]