简体   繁体   中英

Add value to a tuple of list and int in Python3

I was thinking if I have a tuple of int and list:

(5,[2,3])

The first element id represents the sum of the list.

Can I append a value to the list and update the sum at the same time? The results should look something like this:

(10,[2,3,5])

Thanks for any help.

No, you can't because tuples are immutable and therefore the sum can not be modified. You will have to create a new tuple.

>>> t = (5,[2,3])
>>> val = 5
>>> t_new = t[0] + val, t[1] + [val]
>>> t_new
(10, [2, 3, 5])

However, you might want to consider using a mutable data structure in the first place.

You can do this like this:

def addTup(tup, x):
    return (tup[0]+x, tup[1]+[x])

a = (5,[2,3])
addTup(a, 22)

You have to create a new tuple which mainly consists out of the values of the old tuple. This code will add the new item to your list and will update the sum value simultaneously. You cannot simply modify the tuple it self, as tuples are immutable in python, as you can see here .

Since tuples are immutable, you will have to create an entirely new tuple:

_, b = (5,[2,3])
final_results = (sum(b+[5]), b+[5])

Output:

(10, [2, 3, 5])

This is just a fancy version of @FlashTek's answer . The real question is whether there is a purpose to holding these values in a tuple if they are not immutable.

from collections import namedtuple

def add_value(n, x):
    return n._replace(arrsum=n.arrsum+x, arr=n.arr+[x])

SumArray = namedtuple('SumArray', ['arrsum', 'arr'])

s = SumArray(5, [2, 3])

t = add_value(s, 10)
# SumArray(arrsum=15, arr=[2, 3, 10])

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