john
john

Reputation: 263

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.

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. 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)

Upvotes: 0

Views: 77

Answers (2)

Agung Sriwongo
Agung Sriwongo

Reputation: 133

As @Zakaria talhami answer, you need to append a list not multiple values. 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]

Upvotes: 1

Zakaria Talhami
Zakaria Talhami

Reputation: 116

You are appending wrongly, you are passing to the append method multiple values, where you should be appending a list.

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

Upvotes: 2

Related Questions