简体   繁体   English

Python-'tuple'对象不支持项目分配

[英]Python - 'tuple' object does not support item assignment

Hi i am stuck on change value in tuple type. 嗨,我被卡在元组类型的更改值上。 i know i cant change value in tuple type but is there a way to change it ??? 我知道我不能更改元组类型的值,但是有一种方法可以更改它?

a=[('z',1),('x',2),('r',4)]
for i in range(len(a)):
     a[i][1]=(a[i][1])/7  # i wanna do something like this !!!

i wanna change the the number in a to be the probability eg:1/7, 2/7, 4/7 and is there a way to change the number of a to be a float ?? 我想将a中的数字更改为概率,例如:1 / 7、2 / 7、4 / 7,有没有办法将a的数字更改为浮点数? eg 例如

a=[('z',0.143),('x',0.285),('r',0.571)]

The easiest is perhaps to turn the tuples into lists: 最简单的方法可能是将元组变成列表:

a=[['z',1], ['x',2], ['r',4]]

Unlike tuples, lists are mutable, so you'll be able to change individual elements. 与元组不同,列表是可变的,因此您可以更改单个元素。

To change to float it's easy to just do 要更改为float ,只需执行

from __future__ import division # unnecessary on Py 3

One option: 一种选择:

>>> a=[('z',1),('x',2),('r',4)]
>>> a = [list(t) for t in a]
>>> for i in range(len(a)):
            a[i][1]=(a[i][1])/7


>>> a
[['z', 0.14285714285714285], ['x', 0.2857142857142857], ['r', 0.5714285714285714]]

Probably the best way: 最好的方法可能是:

>>> a=[('z',1),('x',2),('r',4)]
>>> a[:] = [(x, y/7) for x, y in a]
>>> a
[('z', 0.14285714285714285), ('x', 0.2857142857142857), ('r', 0.5714285714285714)]

As requested in the comments, to 3 decimal places for "storing and not printing" 根据注释中的要求, “存储而不打印”的小数点后3位

>>> import decimal
>>> decimal.getcontext().prec = 3
>>> [(x, decimal.Decimal(y) / 7) for x, y in a]
[('z', Decimal('0.143')), ('x', Decimal('0.286')), ('r', Decimal('0.571'))]

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

相关问题 TypeError:“元组”对象不支持项目分配 - TypeError: 'tuple' object does not support item assignment 'tuple'对象不支持项目分配 - 'tuple' object does not support item assignment 'tuple' object 不支持项目分配 - DataFrame - 'tuple' object does not support item assignment - DataFrame TypeError:“元组”对象不支持项目分配在非元组对象上 - TypeError: 'tuple' object does not support item assignment On non tuple object 元组作为字典的键说:“元组”对象不支持项目分配 - tuple as key to a dictionary says: 'tuple' object does not support item assignment 列表 object 上的“TypeError: 'tuple' object 不支持项目分配” - “TypeError: 'tuple' object does not support item assignment” on a list object 如何修复:TypeError 'tuple' 对象不支持项目分配 - How to fix a : TypeError 'tuple' object does not support item assignment “元组”对象不支持查找局部最大值时的项目分配 - 'tuple' object does not support item assignment in finding local maximum 收到此错误-'tuple'对象不支持项目分配 - Getting this error - 'tuple' object does not support item assignment TypeError:“元组”对象不支持字典中的项目分配 - TypeError: 'tuple' object does not support item assignment in dictionary
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM