Python: can I modify a Tuple?

て烟熏妆下的殇ゞ 提交于 2019-12-05 17:37:04
UlfR

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

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.

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