I have a list with sublists in it. EG: ([1, 2], [1, 56], [2, 787], [2, 98], [3, 90]) which is created by appending values to it while running a for loop.
I am working in python, and i want to add the 2nd element of each sublist where the 1st elements are same. in my eg:
i want to add 2+56 (both have 1st index as 1), 787+98(both have 1st index as 2) and keep 90 as it is because there is just one element with 1st index as 3.
I’m not sure how to do this.
Here is my code:
import urllib, re
from itertools import groupby
import collections
import itertools, operator
text = urllib.urlopen("some html page").read()
data = re.compile(r'.*?<BODY>(.*?)<HR>', re.DOTALL).match(text).group(1)// storing contents from the BODY tag
values = [line.split() for line in data.splitlines()] //List with the BODY data
/* values contain elements like [[65, 67], [112, 123, 12], [387, 198, 09]]
it contains elements with length 2 and three.
i am just concerned with elements with length 3
in the for loop, i am doing this, and passing it to 2 functions.*/
def function1 (docid, doclen, tf):
new=[];
avgdoclen = 288;
tf = float(x[2]);
doclen = float(x[1]);
answer1 = tf / (tf + 0.5 + (1.5*doclen/avgdoclen));
q = function2(docid, doclen, tf)
production = answer1 * q //this is the production of
new.append(docid) // i want to add all the production values where docid are same.
new.append(production)
return answer1
def function2 (docid, doclen, tf):
avgdoclen = 288;
querylen = 12;
tf= float(x[2]);
answer2 = tf/(tf + 0.5 + (1.5*querylen/avgdoclen));
return answer2
for x in values:
if len(x)==3:
okapi_doc(x[0], x[1], x[2])
okapi_query(x[0], x[1], x[2])
I want to add all the production values where the docid are same. Now when i print new, i get the following output:
['112', 0.3559469323909391]
['150', 0.31715060007742935]
['158', 0.122025819265144]
['176', 0.3862207694241891]
['188', 0.5057900225015092]
['236', 0.12628982528263102]
['251', 0.12166336633663369]
this is not a list. when i print new[0][0] i get 1. I want to get 112 when i print new[0][0]. Is there something wrong with append?
[‘334’, 0.5851519557155408]
1 Answer