I have a list of names:
geneNameList = ['psaA', 'psbF', 'rpl36', 'rpoC1', 'psbK', 'atpB']
and a list of positions:
positionList = ['_1stpos', '_2ndpos', '_3rdpos']
I am trying to add the strings in my position list to each of the names in my list of names so I would end up with a partitionList:
partitionList = ['psaA_1stpos', 'psaA_2ndpos', 'psaA_3rdpos', psbF_1stpos', 'psbF_2ndpos'... 'atpB_3rdpos']
I have this code:
partitionList = []
for i in geneNameList:
for k in positionList:
partition = geneNameList[i] + positionList[k] + ' = '
partitionList.append(partition)
But I keep getting this error:
partition = geneNameList[i] + positionList[k] + ' = '
TypeError: list indices must be integers, not str
geneNameList[i] + positionList[k] + ' = '
to i + k
to add the values of each list.
geneNameList[i]
implies you're trying to get a value based upon it's index in the list. TypeError
is caused because you're indexing the list by a value instead of an integer. (eg geneNameList['psaA']
instead of geneNameList[0]
) positionList = ['_1stpos', '_2ndpos', '_3rdpos']
geneNameList = ['psaA', 'psbF', 'rpl36', 'rpoC1', 'psbK', 'atpB']
partitionList = []
for i in geneNameList:
for k in positionList:
partition = i + k
partitionList.append(partition)
print(partitionList)
['psaA_1stpos',
'psaA_2ndpos',
'psaA_3rdpos',
'psbF_1stpos',
'psbF_2ndpos',
'psbF_3rdpos',
'rpl36_1stpos',
'rpl36_2ndpos',
'rpl36_3rdpos',
'rpoC1_1stpos',
'rpoC1_2ndpos',
'rpoC1_3rdpos',
'psbK_1stpos',
'psbK_2ndpos',
'psbK_3rdpos',
'atpB_1stpos',
'atpB_2ndpos',
'atpB_3rdpos']
You can use itertools.product
to create a cross product of each of the gene names and positions and then join
them together in a list comprehension to produce your partitionList
:
import itertools
geneNameList = ['psaA', 'psbF', 'rpl36', 'rpoC1', 'psbK', 'atpB']
positionList = ['_1stpos', '_2ndpos', '_3rdpos']
partitionList = [''.join(gp) for gp in itertools.product(geneNameList, positionList)]
print(partitionList)
Output:
[
'psaA_1stpos', 'psaA_2ndpos', 'psaA_3rdpos',
'psbF_1stpos', 'psbF_2ndpos', 'psbF_3rdpos',
'rpl36_1stpos', 'rpl36_2ndpos', 'rpl36_3rdpos',
'rpoC1_1stpos', 'rpoC1_2ndpos', 'rpoC1_3rdpos',
'psbK_1stpos', 'psbK_2ndpos', 'psbK_3rdpos',
'atpB_1stpos', 'atpB_2ndpos', 'atpB_3rdpos'
]
If you want the =
on the end of each string, just change ''.join(gp)
to ''.join(gp) + ' = '
in the comprehension.
You are iterating over objects, not over integers.
Python works something like this:
Imagine that you have a list
[cat (an object with it properties), dog, human]
if you make:
for i in list:
you will be iterating over cat, dog, and human, but not over the index of the list.
You have to do this:
for i in range(0, len(list)):
So, now you are iterating over integers (list index) and not objects.
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.