I want to make a function that takes a list eg
[('A',3), ('B',2), ('C',2), ('A',5), ('C',3), ('C',2)]
and then adds the numbers together when the letter is the same. So the above input would produce
[('A',8), ('B',2), ('C',7)].
Could someone please just give me an idea of how to approach this, I'd like to try and do as much as possible myself!
A list is a combination of pairs that creates a linked list. More precisely, a list is either the empty list null, or it is a pair whose first element is a list element and whose second element is a list.
To join pairs of list elements in Python: Use the range() class with a step argument or 2. Use a list comprehension to iterate over the range of indexes. On each iteration, join the list item at the current index with the item at the next index.
Join / Merge two lists in python using + operator In python, we can use the + operator to merge the contents of two lists into a new list. For example, We can use + operator to merge two lists i.e. It returned a new concatenated lists, which contains the contents of both list_1 and list_2.
Yes! Lists: A list is just a special type of pair.
You can use Data.Map
's fromListWith
to construct a map that has the summed values. It's type is this:
fromListWith :: Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
It takes a list of pairs (as you described) as the first arg, if it sees a duplicate, it uses some function (the first arg), to combine the original value with a new one. From there, you can convert this map back into a list of pairs (also a function in Data.Map).
You could do this with pure lists, but it probably won't be that effecient, as you'll be constructing a new list (or portions of it) quite often.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With