Using Python 3 I have 2 lists One has many listseach list ha

Using Python 3:

I have 2 lists.

One has many lists(each list has a letter and a number) [ assume 1000 +].

One has letters [assume 100 + letters].

Listofcombo = [[‘a’, 2], [‘a’, 4], [‘b’, 2], [‘b’, 5], [‘c’, 12], [‘b’, 6], [‘c’, 5], [\'d\', 12], ............]

Listofletter = [‘a’, ‘b’, ‘c’, \'d\', ........]

I want to sum the numbers from the same letters.

such as : \'a\' = 2 + 4 + .......... = suma

\'b\' = 2 + 5 + 6 + ......... = sumb

\'c\' = 12 + 5 + ......... = sumc

\'d\' = 12 + ...... = sumd

.

.

.

.

Output will be:

Outputlist = [[\'a\', suma], [\'b\', sumb], [\'c\', sumc], [\'d\', sumd], ..........]

I know should use for loops. But I do not know where to start w/.

Need helps!

Solution

Python 3 code:

Listofcombo = [[\'a\', 2], [\'a\', 4], [\'b\', 2], [\'b\', 5], [\'c\', 12], [\'b\', 6], [\'c\', 5], [\'d\', 12]]; # initialise Listofcombo
Listofletter = [\'a\', \'b\', \'c\', \'d\']; #initialise Listofletter
mydictionary = {}
for i in range(0,len(Listofcombo)):
   if(Listofcombo[i][0] in mydictionary):
       mydictionary[Listofcombo[i][0]] = mydictionary[Listofcombo[i][0]] + Listofcombo[i][1]
   else:
       mydictionary[Listofcombo[i][0]] = Listofcombo[i][1]      
outputlist = []
for key in mydictionary:
   tmp = []
   tmp.append(key)
   tmp.append(mydictionary[key])
   outputlist.append(tmp)
print(outputlist)

Using Python 3: I have 2 lists. One has many lists(each list has a letter and a number) [ assume 1000 +]. One has letters [assume 100 + letters]. Listofcombo =

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site