简体   繁体   English

在Python3中将值添加到list和int的元组

[英]Add value to a tuple of list and int in Python3

I was thinking if I have a tuple of int and list: 我在想如果我有一个int和list元组:

(5,[2,3])

The first element id represents the sum of the list. 第一个元素id代表列表的总和。

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 . 您不能简单地自行修改元组,因为元组在python中是不变的,如您在此处所见。

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 . 这只是@FlashTek的答案的花哨版本。 The real question is whether there is a purpose to holding these values in a tuple if they are not immutable. 真正的问题是,如果这些值不是不可变的,是否有将它们保存在tuple的目的。

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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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