将嵌套列表中的每个元素乘以常量

2024-04-26 14:32:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经读了很多类似的帖子hereherehere,等等,但是我不能解决我的问题。我有这样一个成对的列表:

 my_list = [[[0, 3], [0, 0]], [[77, 94], [76, 94], [77, 93], [76, 93], [76, 90], [77, 84], [76, 88]], [[25, 31], [10, 0]]]

我想把每个整数乘以-1。我尝试过不同的事情,也遇到了不同的错误,但这是我认为最符合逻辑的代码:

for p in range(len(my_list):
    for q in range(len(mylist[p])):
        my_new_list = [[i,j] * -1 for [i,j] in my_list[p][q]]

而这个根本不起作用!我最终想要的是这样的:

my_new_list = [[[0, -3], [0, 0]], [[-77, -94], [-76, -94], [-77, -93], [-76, -93], [-76, -90], [-77, -84], [-76, -88]], [[-25, -31], [-10, 0]]]

谁能帮我一下吗?你知道吗


Tags: 代码in列表newforlenheremy
2条回答

要对任意深度的列表执行此操作,可以使用以下递归函数:

def negate(list_or_int):
    if isinstance(list_or_int, list):
        # It's a list, so call negate on every element
        return [negate(i) for i in list_or_int]

    # It's an int, so just return the negative
    return -list_or_int

my_new_list = negate(my_list)

您的问题是,您最内部的循环正在创建一个新的子列表,但没有将其适当地分配回(或者分配给一个新列表,或者my_list)。每次都会重新写入上一次迭代的结果。你知道吗

您需要的是一个包含三个循环的列表理解,每个嵌套级别一个循环:

my_new_list = [[[z * -1 for z in y] for y in x] for x in my_list]

如果你能保证你的最里面的列表总是成对的,你可以按照@ShadowRanger的建议简化它,使用一个嵌套的列表comp和两个循环

my_new_list = [[[-a, -b] for a, b in x] for x in my_list]

这相当于

import copy 

my_new_list = copy.deepcopy(my_list)
for x in my_new_list:
    for y in x:
        for i, z in enumerate(y): 
            y[i] = z * -1   # notice the assignment back to the sublist

相关问题 更多 >