简体   繁体   English

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

[英]How to update a tuple and save it new tuple in python

I have a list of 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)]

I want to multiply each odd index element of tuple by 300 thus 1st and 3rd element will be multiplied by 300 and 0th and 2nd element will be multiplied by 200 and save these values at their index. 我想将元组的每个奇数索引元素乘以300,因此第1个和第3个元素将乘以300,第0个和第2个元素将乘以200,并将这些值保存在它们的索引中。 But doing so it gives me below error: 但是这样做给了我下面的错误:

TypeError: 'tuple' object does not support item assignment

How can I modify these values. 如何修改这些值。

Tuples are immutable , so you will need to create new tuples for your desired result. 元组是不可变的 ,因此您需要为所需的结果创建新的元组。 For array-based manipulations, I would strongly recommend you move to a 3rd party library such as NumPy: 对于基于数组的操作,我强烈建议您转到第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]])

But if you insist on using a list of tuples, you can use a list comprehension with a dictionary mapping and enumerate : 但是,如果您坚持使用元组列表,则可以将列表理解与字典映射一起使用并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)]

you should to generate new list of tuples 您应该生成新的元组列表

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

and you can iterate for even and odd indexes 您可以迭代偶数和奇数索引

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

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM