开发者

Python: can I modify a Tuple?

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 dictionar开发者_如何学Goy 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!!


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.


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


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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜