在Python中,要实现两个列表的循环减法,通常使用双循环。
a1 = [0,1,2,3,4]
b1 = [5,6,7,8,9]
for i in range(5):
for j in range(5):
res = b[i] - a[j]
print(res)
输出:
[5, 4, 3, 2, 1, 6, 5, 4, 3, 2, 7, 6, 5, 4, 3, 8, 7, 6, 5, 4, 9, 8,7, 6, 5]
但是,如果有两个需要循环减法的双层列表,则需要一个四层的for循环。
ai = [num0, num1, num2, num3, num4]
bi = [num5, num6, num7, num8, num9]
list1 = [a1, a2, a3, ...., ai]
list2 = [b1, b2, b3, ...., bi]
for i in range(len(list1)):
for j in range(len(list2)):
for p in range(len(ai)):
for q in range(len(bi)):
......
是否有一种方便的方法来实现列表元素的循环减法?
答案 0 :(得分:1)
使用numpy
,第一个示例可以计算为:
import numpy as np
np.subtract.outer(b, a).ravel().tolist()
如果循环中有未定义的......
,这也适用于嵌套列表(第二个示例)。另外,对于嵌套列表而不使用numpy
,您可以尝试:
import itertools
[x - y for x in itertools.chain(*list2) for y in itertools.chain(*list1)]
答案 1 :(得分:1)
首先扁平化列表,然后执行循环减法怎么样?
def flatten(lst):
if all(type(x) == list for x in lst):
return flatten([e for l in lst for e in l])
return lst
def subtract_from(lst2, lst1):
if all(type(x) == list for x in lst1):
lst1, lst2 = flatten(lst1), flatten(lst2)
return [y - x for x in lst1 for y in lst2]
l1 = [0, 1, 2, 3, 4]
l2 = [5, 6, 7, 8, 9]
print(subtract_from(l2, l1))
# [5, 6, 7, 8, 9, 4, 5, 6, 7, 8, 3, 4, 5, 6, 7, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5]
l1 = [[0, 1], [3, 2], [1, 4]]
l2 = [[4, 5], [7, 8], [9, 10]]
print(subtract_from(l2, l1))
# [4, 5, 7, 8, 9, 10, 3, 4, 6, 7, 8, 9, 1, 2, 4, 5, 6, 7, 2, 3, 5, 6, 7, 8, 3, 4, 6, 7, 8, 9, 0, 1, 3, 4, 5, 6]
flatten
是递归的,subtract_from
检查列表是否需要展平。