修改列表中的每个元素

时间:2021-06-30 14:30:14

I thought this question was easy enough but couldn't find an answer.
I have a list of tuples of length 2.
I want to get a list of tuples of length 3 in which the third element is the result of some operation over the other two.
Example:

我认为这个问题很容易,但找不到答案。我有一个长度为2的元组列表。我想得到一个长度为3的元组列表,其中第三个元素是对其他两个元素进行某些操作的结果。例:

for val_1, val_2 in list_of_tuples
    #...
    #some multi line operation
    #...
    val_3 = result
    replace (val_1, val_2) by (val_1, val_2, val_3) in list

Any ideas?

有任何想法吗?

3 个解决方案

#1


3  

You could do something like

你可以做点什么

for index, (val_1, val_2) in enumerate(list_of_tuples):
    # do stuff
    val_3 = # something
    list_of_tuples[index] = (val_1, val_2, val_3)

#2


7  

Use a list comprehension.

使用列表理解。

>>> list_of_tups = [(1,2),(2,3),(3,4)]
>>> [(i,j,i+j) for i,j in list_of_tups]
[(1, 2, 3), (2, 3, 5), (3, 4, 7)]

Now re-assign it back

现在重新分配它

>>> list_of_tups = [(i,j,i+j) for i,j in list_of_tups]

Do not modify lists while iterating as it can have some bad effects.

迭代时不要修改列表,因为它可能会产生一些不良影响。

#3


4  

for a multiline operation, it's easy.

对于多线操作,这很容易。

def f(i, j):
    # math here
    # more math here
    return new_result

and then

接着

result = [(i, j, f(i, j)) for i, j in tuples]

#1


3  

You could do something like

你可以做点什么

for index, (val_1, val_2) in enumerate(list_of_tuples):
    # do stuff
    val_3 = # something
    list_of_tuples[index] = (val_1, val_2, val_3)

#2


7  

Use a list comprehension.

使用列表理解。

>>> list_of_tups = [(1,2),(2,3),(3,4)]
>>> [(i,j,i+j) for i,j in list_of_tups]
[(1, 2, 3), (2, 3, 5), (3, 4, 7)]

Now re-assign it back

现在重新分配它

>>> list_of_tups = [(i,j,i+j) for i,j in list_of_tups]

Do not modify lists while iterating as it can have some bad effects.

迭代时不要修改列表,因为它可能会产生一些不良影响。

#3


4  

for a multiline operation, it's easy.

对于多线操作,这很容易。

def f(i, j):
    # math here
    # more math here
    return new_result

and then

接着

result = [(i, j, f(i, j)) for i, j in tuples]