Python 如何将2个列表配对为1个列表

Python 如何将2个列表配对为1个列表,python,python-2.7,Python,Python 2.7,我有这样一个代码: def datauji(self): uji = [] for x in self.fiturs: a = [x[0],x[-5:]] #I think the problem in this line uji.append(a) return uji with open('DataUjiBaru.csv','wb') as dub: testing = csv.writer(dub)

我有这样一个代码:

def datauji(self):
    uji = []
    for x in self.fiturs:
        a = [x[0],x[-5:]] #I think the problem in this line
        uji.append(a)
    return uji

with open('DataUjiBaru.csv','wb') as dub:
        testing = csv.writer(dub)
        datatest = d.datauji()
        datatest.pop(0)
        for x in datatest:
            testing.writerow(x)
F37,"['1', '0', '0', '0', '1']"
F10,"['8', '4', '5', '6', '4']"
F8,"['0', '0', '2', '0', '0']"
F37,1,0,0,0,1
F10,8,4,5,6,4
F8,0,0,2,0,0
['F37', ['1', '0', '0', '0', '1']]
我想将self.fiturs中的值与self.fiturs中的值配对:

F37,0,1,0,1,1,1,0,1,0,2,1,0,0,0,1
F10,8,4,3,3,3,6,8,5,8,4,8,4,5,6,4
F8,1,0,2,0,0,0,2,0,0,0,0,0,2,0,0
所以我想将索引[0]和索引[-5:]配对,并将其写入csv,csv上的输出如下:

def datauji(self):
    uji = []
    for x in self.fiturs:
        a = [x[0],x[-5:]] #I think the problem in this line
        uji.append(a)
    return uji

with open('DataUjiBaru.csv','wb') as dub:
        testing = csv.writer(dub)
        datatest = d.datauji()
        datatest.pop(0)
        for x in datatest:
            testing.writerow(x)
F37,"['1', '0', '0', '0', '1']"
F10,"['8', '4', '5', '6', '4']"
F8,"['0', '0', '2', '0', '0']"
F37,1,0,0,0,1
F10,8,4,5,6,4
F8,0,0,2,0,0
['F37', ['1', '0', '0', '0', '1']]
我对csv的期望如下:

def datauji(self):
    uji = []
    for x in self.fiturs:
        a = [x[0],x[-5:]] #I think the problem in this line
        uji.append(a)
    return uji

with open('DataUjiBaru.csv','wb') as dub:
        testing = csv.writer(dub)
        datatest = d.datauji()
        datatest.pop(0)
        for x in datatest:
            testing.writerow(x)
F37,"['1', '0', '0', '0', '1']"
F10,"['8', '4', '5', '6', '4']"
F8,"['0', '0', '2', '0', '0']"
F37,1,0,0,0,1
F10,8,4,5,6,4
F8,0,0,2,0,0
['F37', ['1', '0', '0', '0', '1']]

如何解决此问题?

您的代码问题是正确的,可以在以下行中找到:

a = [x[0],x[-5:]]
这将创建如下所示的嵌套项:

def datauji(self):
    uji = []
    for x in self.fiturs:
        a = [x[0],x[-5:]] #I think the problem in this line
        uji.append(a)
    return uji

with open('DataUjiBaru.csv','wb') as dub:
        testing = csv.writer(dub)
        datatest = d.datauji()
        datatest.pop(0)
        for x in datatest:
            testing.writerow(x)
F37,"['1', '0', '0', '0', '1']"
F10,"['8', '4', '5', '6', '4']"
F8,"['0', '0', '2', '0', '0']"
F37,1,0,0,0,1
F10,8,4,5,6,4
F8,0,0,2,0,0
['F37', ['1', '0', '0', '0', '1']]
有两种方法可以解决此问题:

选项1-使用splat*运算符:

a = [x[0],*x[-5:]]
选项2-连接列表的两个部分:

a = x[:1] + x[-5:]
这两种方法都将删除列表的嵌套,并为您提供如下所示的行:

['F37', '1', '0', '0', '0', '1']

然后可以将其写入输出文件。

非常感谢@chrisz