Python:我可以修改元组吗? [英] Python: can I modify a Tuple?

查看:167
本文介绍了Python:我可以修改元组吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个2 D元组(实际上我认为这是一个列表.但是错误表明它是一个元组) 但是无论如何.. 元组的形式为: (floatnumber_val,prod_id) 现在我有一个字典,其中包含key-> prod_id和值prod_name 现在..我想将元组中的prod_id更改为prod_name 所以这是我所做的

I have a 2 D tuple (Actually I thought, it was a list.. but the error says its a tuple) But anyways.. The tuple is of form: (floatnumber_val, prod_id) now I have a dictionary which contains key-> prod_id and value prod_name now.. i want to change the prod_id in tuple to prod_name So this is waht I did

#if prodName is the tuple
# prodDict is the dictionary
for i in range(len(prodName)):
    key = prodName[i][1] # get the prodid
    if prodDict.has_key(key):
        value = prodDict[key]
         prodName[i][1] = value

非常简单 但是我收到一个错误,提示TypeError:'tuple'对象不支持项目分配

umm pretty straightforward but i get an error that TypeError: 'tuple' object does not support item assignment

谢谢!

推荐答案

如果prodName是一个元组列表,并且您想要像说明的那样创建一个新的元组列表,则必须创建一个新的元组,因为元组是不可变的(即无法更改).

If prodName is a list of tuples and you want to create a new list of tuples like you explained, you have to create new tuples since a tuple is immutable (i.e. it can not be changed).

示例:

for i,(floatnumber_val, prod_id) in enumerate(prodName):
  prodName[i] = (floatnumber_val, prodDict.get(prod_id,prod_id))

这篇关于Python:我可以修改元组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆