简体   繁体   中英

Get position in list of items from another list in Python

What I would like to do is find the positions of the female within the fileHeader list and use those positions to append a 0 to the items in myList that match female .

female = ['1', '102', '107', '115']

fileHeader = ['#CHROM', 'POS', '1', '100', '101', '102', '103', '107', '108', '109', '110', 
'111', '114', '115', '116', '117', '118', '11N', '12', '120', '13', 
'14', '15', '16N', '17N', '18N', '19', '2', '21', '22', '23', '24', 
'26', '27', '28', '29', '3', '30', '31', '33', '34', '35', '37', '38', 
'39', '4', '40', '41', '45', '5', '50', '53', '54', '57', '58', '6', 
'67', '68', '7', '71', '72', '73', '74', '75', '77', '78', '79', '8', 
'80', '89', '9', '90', '99', 'F0GM', 'F1Father', 'F1Mother']

myList = ['HE669455_1', '293', 'T', 'T', 'T', 'N', 'T', 'N', 'T', 'T', 'T', 'T', 
'T', 'T', 'N', 'T', 'T', 'T', 'T', 'T', 'T', 'N', 'N', 'N', 'T', 'N', 'N', 'T', 
'N', 'T', 'T', 'T', 'T', 'N', 'T', 'T', 'T', 'N', 'T', 'T', 'T', 'T', 'T', 'T', 
'T', 'T', 'T', 'T', 'N', 'T', 'N', 'T', 'T', 'N', 'N', 'N', 'N', 'T', 'N', 'T', 
'N', 'T', 'T', 'N', 'N', 'T', 'T', 'T', 'N', 'T', 'N', 'N', 'N', 'K', 'T', 'T']

Positions:

[3,6,8,14]

Desired output:

['HE669455_1', '293', 'T0', 'T', 'T', 'N0', 'T', 'N0', 'T', 'T', 'T', 'T', 
'T', 'T0', 'N', 'T', 'T', 'T', 'T', 'T', 'T', 'N', 'N', 'N', 'T', 'N', 'N', 'T', 
'N', 'T', 'T', 'T', 'T', 'N', 'T', 'T', 'T', 'N', 'T', 'T', 'T', 'T', 'T', 'T', 
'T', 'T', 'T', 'T', 'N', 'T', 'N', 'T', 'T', 'N', 'N', 'N', 'N', 'T', 'N', 'T', 
'N', 'T', 'T', 'N', 'N', 'T', 'T', 'T', 'N', 'T', 'N', 'N', 'N', 'K', 'T', 'T']

My attempt at trying to get the positions:

for item in female:
    [fileHeader].index(item)

[fileheader].index() is trying to get the index of a new list with one element in it (fileheader).

You want to append to myList , not fileHandler :

for item in female:
    myList[fileHeader.index(item)] += '0'

I used += 0 because your current myList is filled with strings. If they're lists, it would be:

for item in female:
    myList[fileHeader.index(item)].append(0)

Output:

['HE669455_1', '293', 'T0', 'T', 'T', 'N0', 'T', 'N0', 'T', 'T', 'T', 'T', 'T', 'T0', 'N', 'T', 'T', 'T', 'T', 'T', 'T', 'N', 'N', 'N', 'T', 'N', 'N', 'T', 'N', 'T', 'T', 'T', 'T', 'N', 'T', 'T', 'T', 'N', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'N', 'T', 'N', 'T', 'T', 'N', 'N', 'N', 'N', 'T', 'N', 'T', 'N', 'T', 'T', 'N', 'N', 'T', 'T', 'T', 'N', 'T', 'N', 'N', 'N', 'K', 'T', 'T']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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