简体   繁体   English

如何修改元组列表中元组的每个元素

[英]How to modify each element of a tuple in a list of tuples

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 value to 100 and then reassign them in the same order.我想将每个值乘以 100,然后以相同的顺序重新分配它们。 But doing below, it throws error:但是在下面做,它会抛出错误:

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

How can I modify these values and save them in their places?如何修改这些值并将它们保存在它们的位置?

If you read the docs , you will learn that tuples are immutable (unlike lists), so you cannot change values of tuples.如果您阅读文档,您将了解到元组是不可变的(与列表不同),因此您无法更改元组的值。

Use a list-comprehension:使用列表理解:

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)]

You cannot reassign values to tuples because they are immutable.您不能将值重新分配给元组,因为它们是不可变的。 Try creating a new 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)]
my_list = [tuple(map(lambda x: x*100, item)) for item in my_list]

Tuples are immutable.元组是不可变的。 A list of tuples is not the best structure for what you're looking to do.元组列表不是您要执行的操作的最佳结构。 If you can use a 3rd party library, I recommend NumPy:如果您可以使用 3rd 方库,我推荐 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]])

The alternative is a list comprehension, which doesn't work in place.另一种方法是列表理解,它不起作用。

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

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