更改列表列表并在python中创建一个新列表

时间:2018-11-04 14:25:45

标签: python

我有一个很大的列表清单,例如这个小例子:

small example:

mylist = [['D00645:305:CCVLRANXX:2:2110:19904:74155', '272', 'chr1', '24968', '0', '32M', '*', '0', '0', 'GACAACACAGCCCTCATCCCAACTATGCACAT'], ['D00645:305:CCVLRANXX:2:2201:12674:92260', '256', 'chr1', '24969', '0', '31M', '*', '0', '0', 'ACAACACAGCCCTCATCCCAACTATGCACAT']

,我想创建一个具有相同数量的内部列表的列表子列表。但我将更改内部列表。在新的列表列表中,内部列表将有6列。

1st column : the 3rd column of old inner list. they start with 'chr' 
2nd column : (the 4rh column in old inner list) - 1
3rd column : ((the 4rh column in old inner list) - 1) + length (10th column in old inner list)
4th column : the 1st column in old inner list
5th column : only 0. as integer
6th column : should be "+" or "-". if in old inner list the 2nd column is 272, in new inner list 6th column would be "-" otherwise that should be "+". 

新的列表列表如下所示:

newlist = [['chr1', 24967, 24999, 'D00645:305:CCVLRANXX:2:2110:19904:74155', 0, "-"], ['chr1', 24968, 24999, 'D00645:305:CCVLRANXX:2:2201:12674:92260', 0, "+"]]

我正在尝试使用以下命令在python中执行此操作,但是它不能按照我的要求运行。你知道如何解决吗?

newlist = []
for i in mylist:
    if i[1] ==272:
        sign = '-'
    else:
        sign = '+'
    newlist.append(i[2], int(i[3])-1, int(i[3])-1+len(i[9]), i[0], 0, sign)

2 个答案:

答案 0 :(得分:2)

您追加错误,您将多个值传递给append方法,您应该在其中追加列表。

要解决此问题,请更改附录中的代码,然后将其包裹在“ []”周围,

newlist.append([i[2], int(i[3])-1, int(i[3])-1+len(i[9]), i[0], 0, sign])

答案 1 :(得分:1)

作为@Zakaria talhami答案,您需要附加一个列表,而不是多个值。您可以使用列表推导获得相同的结果。通常,它比添加空列表快。看到: Why is a list comprehension so much faster than appending to a list?

使用列表理解:

newlist = [[j[2],int(j[3])-1,int(j[3])-1+len(j[9]),j[0],0,"-" if j[1] == '272' else "+"] for j in mylist]