Python: can I modify a Tuple?

99封情书 提交于 2019-12-10 08:43:46

问题


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

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

Thanks!!


回答1:


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

Example:

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



回答2:


Tuples are not mutable, you cannot change them.

The thing to do is probably to find out why you are creating tuples instead of the list you expected.




回答3:


Short answer: you cannot.

Tuples are immutable. Lists are mutable. That's really the key distinction.

If you want to mutate an ordered collection of items in Python it's going to have to be a list. If you want to stick to tuples you're going to have to make a new one. If I've understood you correctly you are starting with:

prodName = [(1.0, 1), (1.1, 2), (1.2, 3)]
prodDict = {1: 'name_1', 2: 'name_2', 3: 'name_3'}

So, you can get the list you want with:

new_prodName = [(f, prodDict[id]) for f, id in prodName)]

This will fail if the id isn't found in the prodDict dict. If you want it to fail early that's great. If not, you can set a default (ex: None) using .get():

new_prodName = [(f, prodDict.get(id, None)) for f, id in prodName)]



回答4:


Unfortunately, you can't modify the tuple. Use lists instead.




回答5:


prodName[i] = tuple(prodName[i][0], value)


来源:https://stackoverflow.com/questions/7353589/python-can-i-modify-a-tuple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!