简体   繁体   中英

How to replace a tuple in sorted list of tuples basing on first value Python

I am new to python, and I'm looking for help with solving the following problem

I need to create a sorted list of tuples/dictionaries basing on provided data. Then when new data is provided, and has the same first key, I want to replace it's value with new one. To be more clear I will give example... Imagine I have data, which looks as follows :

data = [(1, 100), (2, 200), (4, 400), (7, 900)]

Then I have new entry from user for example:

(4,500)

So, now I want to replace this tuple with (4,400) to this one with (4,500) . I know that tuples are immutable, thus I don't want to update anything, just erase previous one basing on the key (here: 4) and replace it with new tuple.

So far I used a class from another stack which insert every new entry (tuple) in a sorted way to a list of tuples, and I want it to stay this way, because further I need to calculate closest lower and higher number to provided one in case if its not in a list.

My code looks as follows:

from bisect import bisect_left


class KeyWrapper:
    def __init__(self, iterable, key):
        self.it = iterable
        self.key = key

    def __getitem__(self, i):
        return self.key(self.it[i])

    def __len__(self):
        return len(self.it)

data = [(1, 100), (2, 200), (4, 400), (7, 900)]
data.sort(key=lambda c: c[0])

newcol = (3, 500)

bslindex = bisect_left(KeyWrapper(data, key=lambda c: c[0]), newcol[0])
data.insert(bslindex, newcol)

The output looks as follows:

[(1,100),(2,200),(3,500),(4,400),(7,900)]

And providing new variable for ex. newcols2 = (3,600) , basing on first element of a tuple (here 3) I want to be output like:

[(1,100),(2,200),(3,600),(4,400),(7,900)]

How about this?

data = [(1, 100), (2, 200), (4, 400), (7, 900)]
new = (4, 500)

# Filter out matching
data = [i for i in data if i[0] != new[0]]
# Add the new
data.append(new)
# Re-sort
data = sorted(data, key=lambda x: x[0])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM