简体   繁体   English

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

[英]changing a list of lists and make a new one in python

I have a big list of lists like this small example: 我有一个很大的列表列表,像这个小例子:

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']

and I want to make a sub list of lists with the same number of inner lists. 我想用相同数量的内部列表制作列表的子列表。 but I will change the inner lists. 但我将更改内部列表。 in the new list of lists, the inner list would have 6 columns. 在新的列表列表中,内部列表将有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 "+". 

the new list of lists will look like this: 新的列表列表将如下所示:

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

I am trying to do that in python using the following command but it does not work like what I want. 我正在尝试使用以下命令在python做到这一点,但它不能像我想要的那样工作。 do you know how to fix it? 你知道如何解决吗?

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)

You are appending wrongly, you are passing to the append method multiple values, where you should be appending a list. 您错误地追加,正在将多个值传递给append方法,您应该在其中追加列表。

To fix the problem, change the code in the append and wrap around it "[ ]", like so 要解决此问题,请更改附加中的代码,并在其周围加上“ []”,如下所示

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

As @Zakaria talhami answer, you need to append a list not multiple values. 作为@Zakaria talhami的答案,您需要附加一个列表,而不是多个值。 You can obtain the same result using list comprehension. 您可以使用列表推导获得相同的结果。 Usually it is faster than appending an empty list. 通常,它比添加空列表快。 see: Why is a list comprehension so much faster than appending to a list? 请参阅: 为什么列表理解比附加到列表这么快?

Using list comprehension : 使用列表理解:

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM