Python: refresh tuple list

I have a list of tuples like this:

list = [(1, 'q'), (2, 'w'), (3, 'e'), (4, 'r')]

and I'm trying to create an update to the update function (item, num) that searches for an item in a list and then changes the number.

for example, if I use update (w, 6), the result will be

list = [(1, 'q'), (6, 'w'), (3, 'e'), (4, 'r')] 

I tried this code but I had an error

 if item in heap: heap.remove(item) Pushheap(item,num) else: Pushheap(item,num) 

Is pushheap a feature that pushes tuples in a heap any ideas?

+6
source share
3 answers

You can simply browse the list looking for the tuple with the desired letter, and replace the entire tuple (you cannot change the tuples), breaking out of the loop when you find the necessary element. For instance,

 lst = [(1, 'q'), (2, 'w'), (3, 'e'), (4, 'r')] def update(item, num): for i, t in enumerate(lst): if t[1] == item: lst[i] = num, item break update('w', 6) print(lst) 

Exit

 [(1, 'q'), (6, 'w'), (3, 'e'), (4, 'r')] 

However, you should seriously consider using a dictionary instead of a list of tuples. A dictionary search is much more efficient than performing a linear scan through a list.

+5
source

As noted in the comments, you are using an immutable data structure for the data items you are trying to modify. Without further context, it seems you need a dictionary, not a list of tuples, and it looks like you want the second element in the tuple (letter) to be key, since you plan to modify the number.

Using these assumptions, I recommend converting the list of tuples to a dictionary and then using the usual dictionary assignment. It also assumes that the order is not important (if there is, you can use OrderedDict ) and that the same letter does not appear twice (if so, then only the last number will be in the dict).

 >>> lst = [(1, 'q'), (2, 'w'), (3, 'e'), (4, 'r')] >>> item_dict = dict(i[::-1] for i in lst) >>> item_dict {'q': 1, 'r': 4, 'e': 3, 'w': 2} >>> item_dict['w'] = 6 >>> item_dict {'q': 1, 'r': 4, 'e': 3, 'w': 6} 
+3
source

Tuples are an immutable object. This means that after they are created, you cannot change the contents.

However, you can get around this by replacing the tuple that you want to change. Maybe something like this:

 def change_item_in_list(lst, item, num): for pos, tup in enumerate(lst): if tup[1] == item: lst[pos] = (num, item) return l = [(1, 'q'), (2, 'w'), (3, 'e'), (4, 'r')] print(l) change_item_in_list(l, 'w', 6) print(l) 

But as @brianpck already said, you probably want a (ordered) -dictionary instead of a list of tuples.

+1
source

All Articles