如何在python中更新元组并将其保存为新元组

时间:2018-12-20 11:53:41

标签: python arrays 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)]

我想将元组的每个奇数索引元素乘以300,因此第一个和第三个元素将乘以300,第0个和第二个元素将乘以200,并将这些值保存在它们的索引中。但是这样做会给我以下错误:

TypeError: 'tuple' object does not support item assignment

如何修改这些值。

2 个答案:

答案 0 :(得分:1)

Tuples are immutable,因此您需要为所需的结果创建新的元组。对于基于数组的操作,强烈建议您移至第3方库,例如NumPy:

import numpy as np

A = np.array(my_list)
A *= np.tile([200, 300], A.shape[1] // 2)

print(A)

array([[ 24.99401569, 111.55958176, 193.62900257, 166.2896812 ],
       [ 37.51572967, 185.13922691, 169.64366436, 242.64471531],
       [ 13.84676099,  64.92026746, 198.3550787 , 124.09249842]])

但是,如果您坚持使用元组列表,则可以使用具有字典映射和enumerate的列表理解:

d = {0: 200, 1: 300}

res = [tuple(val * d[idx % 2] for idx, val in enumerate(tup)) for tup in my_list]

print(res)

[(24.99401569366455, 111.5595817565918, 193.62900257110596, 166.28968119621277),
 (37.515729665756226, 185.13922691345215, 169.6436643600464, 242.64471530914307),
 (13.846760988235474, 64.92026746273041, 198.3550786972046, 124.092498421669)]

答案 1 :(得分:0)

您应该生成新的元组列表

[(el[0]*200, el[1]*300, el[2]*200, el[3]*300) for el in my_list]

您可以迭代偶数和奇数索引

[tuple(el * (200 if idx % 2 == 0 else 300) for idx, el in enumerate(tup)) for tup in my_list]