Reputation: 19
I'm working on a project in Python and came across a problem. I have a long data set that is a list of two ply lists that looks like this:
[('A', 15), ('C', 125), ('L', 37), ('J', 215), ('M', 829), etc.]
What I want to do is insert another data set that has the same first element but a different second like this:
[('A', 2), ('C', 4), ('L', 9), ('J', 7), ('M', 15), etc.]
so that the first set of data has three elements to each list, like this:
[('A', 15, 2), ('C', 125, 4), ('L', 37, 9), ('J', 215, 7), ('M', 829, 15), etc.]
What kind of code would I need to set up to get this third set of data to add its second element to my first set of data?
Upvotes: 1
Views: 75
Reputation: 143
If this is by position and the lists have equal length, you can try this:
l1 = [('A', 15), ('C', 125), ('L', 37), ('J', 215), ('M', 829)]
l2 = [('A', 2), ('C', 4), ('L', 9), ('J', 7), ('M', 15)]
l_combined = [(i[0][0], i[0][1], i[1][1]) for i in zip(l1, l2)]
What you basically do is to combine both lists into a larger tuple, where you then access each element by position.
Upvotes: 2