如何在python中修改元组的每个元素

时间:2018-11-15 15:55:21

标签: python list tuples

我有一个元组列表:

my_list = 
 [(0.12497007846832275, 0.37186527252197266, 0.9681450128555298, 0.5542989373207092), 
 (0.18757864832878113, 0.6171307563781738, 0.8482183218002319, 0.8088157176971436), 
 (0.06923380494117737, 0.2164008915424347, 0.991775393486023, 0.41364166140556335)]

我想将每个值乘以100,然后以相同的顺序重新分配它们。但是,在下面执行此操作会引发错误:

for i in range(len(my_list)):
    for j in range(4):
        my_list[i][j] = 100 * my_list[i][j]

TypeError: 'tuple' object does not support item assignment

如何修改这些值并将其保存在它们的位置?谢谢

3 个答案:

答案 0 :(得分:6)

如果您阅读docs,将会了解元组是不可变的(与列表不同),因此您无法更改元组的值。

使用列表理解:

my_list = [(0.12497007846832275, 0.37186527252197266, 0.9681450128555298, 0.5542989373207092), 
           (0.18757864832878113, 0.6171307563781738, 0.8482183218002319, 0.8088157176971436), 
           (0.06923380494117737, 0.2164008915424347, 0.991775393486023, 0.41364166140556335)]

my_list = [tuple(y * 100 for y in x ) for x in my_list]
# [(12.497007846832275, 37.186527252197266, 96.814501285552979, 55.429893732070923),   
#  (18.757864832878113, 61.713075637817383, 84.821832180023193, 80.881571769714355), 
#  (6.9233804941177368, 21.640089154243469, 99.177539348602295, 41.364166140556335)]

答案 1 :(得分:1)

您不能将值重新分配给元组,因为它们是不可变的。尝试创建一个新的元组列表:

my_list = [(0.12497007846832275, 0.37186527252197266, 0.9681450128555298, 0.5542989373207092), 
 (0.18757864832878113, 0.6171307563781738, 0.8482183218002319, 0.8088157176971436), 
 (0.06923380494117737, 0.2164008915424347, 0.991775393486023, 0.41364166140556335)]
my_list = [tuple(map(lambda x: x*100, item)) for item in my_list]

答案 2 :(得分:1)

组是不可变的。元组列表不是您想要执行的操作的最佳结构。如果您可以使用第三方库,建议您使用NumPy:

import numpy as np

A = np.array(my_list)
A *= 100

print(A)

array([[ 12.49700785,  37.18652725,  96.81450129,  55.42989373],
       [ 18.75786483,  61.71307564,  84.82183218,  80.88157177],
       [  6.92338049,  21.64008915,  99.17753935,  41.36416614]])

替代方法是列表理解,这不适用于地方。