简体   繁体   中英

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. 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:

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 :

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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