Reputation: 9213
I essentially want to do an Index-Match(think Excel) type formula in Python to replace the None in tuple_list with an the equivalent value in tuple_list1.
My code:
tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", None), ("plum", None)]
tuple_list1 = [("orange, 10"),("plum", 10),("kumquat", 23)]
for item in tuple_list:
if item[1] == None:
item[1] = tuple_list[tuple_list1.index(item[0])][1]
print tuple_list
My error:
ValueError: 'kumquat' is not in list
Desired Output:
[("pineapple", 5), ("cherry", 7), ("kumquat", 23), ("plum", 10)]
Upvotes: 1
Views: 155
Reputation:
You can iterate through tuple_list
and tuple_list1
and filter out a new list were all the tuples that had the same value by index of 0 in, right there and now. And then replace it in the new list which is still iterating until it is finished.
Heres my soulution. This creates a new list.
tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", None), ("plum", None)]
tuple_list1 = [("orange", 10),("plum", 10),("kumquat", 23)]
tuple_list = [(v1[0], [v2 for v2 in tuple_list1 if v2[0] == v1[0]][0][1]) if v1[1] == None else v1 for v1 in tuple_list]
print tuple_list
Upvotes: 0
Reputation: 3273
You probably should use dictionaries for that, but if you need to use this data format, you need to filter the tuple_list1
to get the data you need.
tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", None), ("plum", None)]
tuple_list1 = [("orange", 10),("plum", 10),("kumquat", 23)]
for key, item in enumerate(tuple_list):
if item[1] == None:
tuple_list[key] = (item[0], [x for x in tuple_list1 if x[0] == item[0]][0][1])
print tuple_list
Upvotes: 1
Reputation: 542
You got your tuple_list and tuple_list1 reversed. the breaking line should be:
tuple_list1[tuple_list.index(item)][1]
also shouldn't be using [0] on the item, you're not looking for a component of a tuple, you're looking for the index of the whole tuple
Another issue is going to be that you can't modify an element of a tuple. They're immutable. You'll have to create a new tuple and replace the old one
Here's some code that will do what you want it to do:
tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", None), ("plum", None)]
tuple_list1 = [("orange, 10"),("plum", 10),("kumquat", 23)]
for item in tuple_list:
if item[1] == None:
ind = tuple_list.index(item)
ind2 = [i for i in range(len(tuple_list1)) if tuple_list1[i][0] == item[0]][0]
tuple_list[ind] = (item[0], tuple_list1[ind2][1])
print tuple_list
Upvotes: 0