简体   繁体   中英

Python: Modify tuple in list

My actual output looks like this:

target = [([('Kid', '200-5'), (u'Rock', '200-6')], u's725')]

How can I modify data in the tuple such that I can return, at the end, the modified list which has the same format as target?

For example: I'd like to change 'kid' in 'adult', such that the rest stays, ie I receive: newTarget = [([('adult', '200-5'), (u'Rock', '200-6')], u's725')]

My idea: Copy all the data of target in a temporary list, modify things and create the same format as in target.

BUT: How can I achieve this concretely? Until now, I could Change and modify things, but I didn't get the same format again...

Have you tried this?

l = list(target[0][0][0])
l[0] = 'Adult'
target[0][0][0] = tuple(l)

Since tuples are immutable, you cannot modify their elements—you must replace them with new tuples. Lists are mutable, so you can replace individual parts as needed:

>>> x = [(1, 2), (3, 4), 5]
>>> x[0] = (x[0][0], 0)
>>> x
[(1, 0), (3, 4), 5]

In the above example, I create a list x containing tuples as its first and second elements and an int as its third. On the second line, I construct a new tuple to swap in to the first position of x, containing the first element of the old tuple, and a new element 0 to replace the 2 .

You will need recursion if you need to be more flexible

target = [([('Kid', '200-5'), (u'Rock', '200-6')], u's725')]

def search_and_replace(inlist):
        res = []
        for t in inlist:
            if isinstance(t, list):
                res.append(search_and_replace(t))
            elif isinstance(t, tuple):
                t1, t2 = t 
                if t1 == 'Kid':
                    t1 = 'adult'
                elif isinstance(t1, list):
                    t1 = search_and_replace(t1)
                res.append((t1, t2)) 
            else:
                res.append(t)

        return  res 


print search_and_replace(target) 

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