在Python中,如何将多维列表中的每个元素乘以一个数字?

huangapple go评论72阅读模式
英文:

In Python, how to multiply each element in a multidimensional list by a number?

问题

我有一个包含浮点数(或整数,我认为在我们的情况下没有关系)的多维列表,比如一个名为lst的列表 = [[1,2],[1,1],[4,5]]。列表的维度未指定:它不一定是2。lst也可以是一个三维列表,类似于[[[1,2],[1,1],[4,5]],[[1,2],[1,1],[4,5]]]。我想要将lst中的每个数字都乘以给定的数字,比如2。

如果lst是一维的,可以通过定义lst2 = [i*2 for i in lst]来实现这一点。然而,对于高维列表,这种方法不适用。也可以使用循环逐个元素地执行此操作,但由于未指定lst的维度,所需的循环数量是未知的。

有人有办法如何干净地做到这一点吗?

英文:

I have a multidimensional list of floats (or ints, I think it doesn't matter in our case), say, a list named lst = [[1,2],[1,1],[4,5]]. The dimension of the list is not specified: it doesn't have to be 2. lst could also be a 3-dimensional list, which is something like [[[1,2],[1,1],[4,5]],[[1,2],[1,1],[4,5]]]. I want to multiply each number in lst by a given number, say, 2.

If lst is one-dimensional, one way to do this is to define lst2 = [i*2 for i in lst]. However, this doesn't work for a high dimensional list. One could also use loops to do this element by element, but since the dimension of lst is not specified, the number of loops needed is unknown.

Does anyone have some idea how to do this neatly?

答案1

得分: 3

你可以使用递归来完成这个任务,例如:

lst = [[[1, 2], [1, 1], [4, 5]], [[1, 2], [1, 1], [4, 5]]]

def multiply(obj, number):
    if isinstance(obj, list):
        return [multiply(v, number) for v in obj]
    else:
        return obj * number

new_lst = multiply(lst, 2)
print(new_lst)

打印结果:

[[[2, 4], [2, 2], [8, 10]], [[2, 4], [2, 2], [8, 10]]]
英文:

You can use recursion for the task, e.g.:

lst = [[[1, 2], [1, 1], [4, 5]], [[1, 2], [1, 1], [4, 5]]]

def multiply(obj, number):
    if isinstance(obj, list):
        return [multiply(v, number) for v in obj]
    else:
        return obj * number

new_lst = multiply(lst, 2)
print(new_lst)

Prints:

[[[2, 4], [2, 2], [8, 10]], [[2, 4], [2, 2], [8, 10]]]

答案2

得分: 1

如果您想要更通用的东西,您可以创建一个适用于任何函数的工具:

def nested_map(func, obj):
    if not isinstance(obj, list):
        return func(obj)
    return [nested_map(func, x) for x in obj]

nested_map(lambda n: 2*n, lst)
# [[[2, 4], [2, 2], [8, 10]], [[2, 4], [2, 2], [8, 10]]]
英文:

If you want something more generally useful, you could make this util that works with any function:

def nested_map(func, obj):
    if not isinstance(obj, list):
        return func(obj)
    return [nested_map(func, x) for x in obj]


nested_map(lambda n: 2*n, lst)
# [[[2, 4], [2, 2], [8, 10]], [[2, 4], [2, 2], [8, 10]]]

答案3

得分: 0

你可以编写一个通用函数,使其在任意维度的嵌套列表之间工作:

def broadcast(a, b, oper):
    match = isinstance(a, list), isinstance(b, list)
    if match == (False, False): return oper(a, b)
    if match == (True, False):  return [broadcast(i, b, oper) for i in a]
    if match == (False, True):  return [broadcast(a, i, oper) for i in b]
    a = a + a[-1:] * (len(b) - len(a))
    b = b + b[-1:] * (len(a) - len(b))
    return [broadcast(i, j, oper) for i, j in zip(a, b)]

# 输出示例:

A = [ [1,2,3],
      [4,5,6],
      [7,8,9] ]
B = [ [10,20,30] ]
C = [100,200,300]

mult = lambda a, b: a * b
add  = lambda a, b: a + b

print(*broadcast(A, 10, mult), sep="\n")
[10, 20, 30]
[40, 50, 60]
[70, 80, 90]

print(*broadcast(A, B, add), sep="\n")
[11, 22, 33]
[14, 25, 36]
[17, 28, 39]

print(*broadcast(A, C, add), sep="\n")
[101, 102, 103]
[204, 205, 206]
[307, 308, 309]

print(*broadcast(B, C, add), sep="\n")
[110, 120, 130]
[210, 220, 230]
[310, 320, 330]
英文:

You could write a general function to make this work between nested lists of any dimensions:

def broadcast(a,b,oper):
    match = isinstance(a,list),isinstance(b,list)
    if match == (False,False): return oper(a,b)
    if match == (True,False):  return [broadcast(i,b,oper) for i in a]
    if match == (False,True):  return [broadcast(a,i,oper) for i in b]
    a = a + a[-1:]*(len(b)-len(a))
    b = b + b[-1:]*(len(a)-len(b))
    return [broadcast(i,j,oper) for i,j in zip(a,b)]

outputs:

A = [ [1,2,3],
      [4,5,6],
      [7,8,9] ]
B = [ [10,20,30] ]
C = [100,200,300]

mult = lambda a,b: a*b
add  = lambda a,b: a+b

print(*broadcast(A,10,mult),sep="\n")
[10, 20, 30]
[40, 50, 60]
[70, 80, 90]

print(*broadcast(A,B,add),sep="\n")
[11, 22, 33]
[14, 25, 36]
[17, 28, 39]

print(*broadcast(A,C,add),sep="\n")
[101, 102, 103]
[204, 205, 206]
[307, 308, 309]

print(*broadcast(B,C,add),sep="\n")
[110, 120, 130]
[210, 220, 230]
[310, 320, 330]

huangapple
  • 本文由 发表于 2023年7月13日 00:26:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76672683.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定